4

如何通过 Apache CSV 以 UTF-8 编写 CSV 文件?

我正在尝试通过以下代码生成 csv,其中 Files.newBufferedWriter() 默认将文本编码为 UTF-8,但是当我在 excel 中打开生成的文本时,会出现无意义的字符。

我像这样创建 CSVPrinter:

CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(Paths.get(filePath)), CSVFormat.EXCEL);

接下来我设置标题

csvPrinter.printRecord(headers);

然后在循环中的下一个我像这样将值打印到写入器中

csvPrinter.printRecord("value1", "valu2", ...);

我还尝试将文件上传到在线 CSV lint 验证器,它告诉我使用的是 ASCII-8BIT 而不是 UTF-8。我做错了什么?

4

1 回答 1

12

Microsoft 软件倾向于采用 windows-12* 或 UTF-16LE 字符集,除非内容以软件将用来识别字符集的字节顺序标记开头。尝试在文件开头添加字节顺序标记:

try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath))) {

    writer.write('\ufeff');

    CSVPrinter csvPrinter = new CSVPrinter(writer);

    //...
}
于 2019-07-19T14:50:38.250 回答