如何通过 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);
然后在循环中,我像这样将值打印到 writer
csvPrinter.printRecord("value1", "valu2", ...);
我还尝试将文件上传到在线 CSV lint validator ,它告诉我我使用的是 ASCII-8BIT 而不是 UTF-8。我做错了什么?
最佳答案
Microsoft 软件倾向于采用 windows-12* 或 UTF-16LE 字符集,除非内容以 byte order mark 开头。软件将使用它来识别字符集。尝试在文件开头添加字节顺序标记:
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath))) {
writer.write('\ufeff');
CSVPrinter csvPrinter = new CSVPrinter(writer);
//...
}
关于java - 通过 UTF-8 中的 Apache CSV 生成 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57112252/