Java:在不同的列上打印csv?

时间:2016-12-12 13:57:53

标签: java sql csv multiple-columns

我想在CSV文件上打印查询表结果。

我尝试使用此代码:

PrintWriter csvWriter = new PrintWriter(new File(path + "SqlClient_" + date + ".csv")) ;
ResultSetMetaData meta = rs.getMetaData() ; 
int numberOfColumns = meta.getColumnCount() ; 
String dataHeaders = "\"" + meta.getColumnName(1) + "\"" ; 
for (int i = 2 ; i < numberOfColumns + 1 ; i ++ ) { 
       dataHeaders += ",\"" + meta.getColumnName(i) + "\"" ;
    }
    csvWriter.println(dataHeaders) ;
    while (rs.next()) {
        String row = "\"" + rs.getString(1) + "\""  ; 
        for (int i = 2 ; i < numberOfColumns + 1 ; i ++ ) {
             row += ",\"" + rs.getString(i) + "\"" ;
        }
        csvWriter.println(row) ;
    }
    csvWriter.close();

这是我获得的:

title1","title2","title3"
"date1","date2","date3"
....

这是在单个列中写入,而是我想写在不同的列上,如:

title1 | title2 | title3 
data1| data2 | data3 |

有一个特殊的命令可以将字符串拆分成不同的列吗?

3 个答案:

答案 0 :(得分:1)

为什么不为此使用StringBuilder。假设您从数据库调用中获取了一个包含YourClass类型列表的结果集。调用以下实用程序并将writer传递给它。

伪代码:

public void writeToCSV(FileWriter writer){

StringBuilder sb=new StringBuilder();
for (YourClass data: yourresultSet){

sb.append("\"");
sb.append(data.getColumn1);
sb.append"\"";
sb.append(",\"")
sb.append(data.getColumn2);
sb.append("\"");
sb.append('\n'); //new line after the column

writer.write(sb.toString());
sb.delete(0,sb.length());

}

}

并测试你的结果

public class ReadCSV{

public static void main(String[] args) {

    String csvFile = "your.csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {

        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] title= line.split(cvsSplitBy);

            System.out.println("Columns [Column1= " + title[0] + " , Column2=" + title[1] + "]");

        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
}

答案 1 :(得分:0)

CSV文件使用分隔符来分隔列,所以我猜你的分隔符是,(逗号)。

您应该做的是打印以逗号分隔的标题的值,然后附加新的行分隔符(\n)以创建新列。与行值相同。

有关详细信息,请参阅此example

答案 2 :(得分:-1)

我相信您可以将此行更改为您认为更适合您的行:

row += ",\"" + rs.getString(i) + "\"";