我正在嘗試使用這個庫commons-csv (1.5)來生成 csv 文件,我制作了一個簡單的程序來查看結果:String SAMPLE_CSV_FILE = "./sample.csv"; try ( BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE)); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.EXCEL .withHeader("ID", "Name", "Designation", "Company")); ) { csvPrinter.printRecord("1", "Name1 ", "CEO", "Google"); csvPrinter.printRecord("2", "Name2", "CEO", "Microsoft"); csvPrinter.flush(); }我的 CSV 生成良好,但標題和數據在每一列中沒有分開,當我打開 CSV 文件時,我在第一列中看到所有數據和標題我還沒有找到好的 CSVFormat,如何將它們分開?
2 回答

互換的青春
TA貢獻1797條經驗 獲得超6個贊
所選答案并未真正顯示如何確保將逗號設置為分隔符。
要告訴 excel 逗號應該用作分隔符,請打印printer.printRecord("SEP=,");為文件中的第一條記錄。它是一個 excel 可以理解的命令,它不會顯示在您的文件輸出中。
try (CSVPrinter printer = new CSVPrinter(new FileWriter("file.csv"),CSVFormat.EXCEL)) {
printer.printRecord("SEP=,"); //this line does the margic.
printer.printRecord("Column A","Column B","Column C");
} catch (IOException ex) {
}
添加回答
舉報
0/150
提交
取消