CSVPrinter 数据似乎未按列分隔

CSVPrinter datas appears not separated in columns

我正在尝试使用这个库 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 生成良好,但 header 和数据在每一列中没有分开,当我打开 CSV 文件时,我在第一列中看到所有数据和 header

我还没有找到好的 CSV 格式,如何将它们分开?

当我 运行 你的程序时,我按预期得到了用逗号分隔的所有列。如果您使用 Excel 打开文件,请确保您已选择逗号而不是制表符作为分隔符。

选择的答案并没有真正说明如何确保将逗号设置为分隔符。

要告诉 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) {
    
}