6

csv 文件打开乱码,有哪些方法可以解决?

 3 years ago
source link: http://www.blogjava.net/paulwong/archive/2021/03/23/435832.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

csv 文件打开乱码,有哪些方法可以解决?

Excel 在读取 csv 的时候是通过读取文件头上的 bom 来识别编码的,这导致如果我们生成 csv 文件的平台输出无 bom 头编码的 csv 文件(例如 utf-8 ,在标准中默认是可以没有 bom 头的),Excel 只能自动按照默认编码读取,不一致就会出现乱码问题了。

掌握了这点相信乱码已经无法阻挡我们前进的步伐了:只需将不带 bom 头编码的 csv 文件,用文本编辑器(工具随意,推荐 notepad++ )打开并转换为带 bom 的编码形式(具体编码方式随意),问题解决。

当然,如果你是像我一样的码农哥哥,在生成 csv 文件的时候写入 bom 头更直接点,用户会感谢你的。

附录:对于 utf-8 编码,unicode 标准中是没有 bom 定义的,微软在自己的 utf-8 格式的文本文件之前加上了EF BB BF三个字节作为识别此编码的 bom 头,这也解释了为啥大部分乱码都是 utf-8 编码导致的原因

SPRING BATCH中生成CSV文件时的解决方案:
new FlatFileItemWriterBuilder<T>()
      .name(itemWriterName)
      .resource(outputResource)
      .lineAggregator(lineAggregator)
      .headerCallback(
      h -> {
               System.out.println(header);
               h.write('\uFEFF');//只需加这一行
               h.write(header);
           }
      )
      .build();
https://stackoverflow.com/questions/48952319/send-csv-file-encoded-in-utf-8-with-bom-in-java

posted on 2021-03-23 10:30 paulwong 阅读(21) 评论(0)  编辑  收藏 所属分类: SPRINGSRPING BATCH


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK