csv文件导出UTF-8乱码解决方案
文末有个自己开发过程中遇到的问题。
原因:缺少bom设置
设置bom
byte[] bom ={(byte) 0xEF,(byte) 0xBB,(byte) 0xBF};
业务代码:
public ResultMap appleExportCSV() throws Exception {
File bcpFile = new File("G:\\csv\\test.csv"); //生成文件地址路径
byte[] bom ={(byte) 0xEF,(byte) 0xBB,(byte) 0xBF};
FileOutputStream bcpFileWriter = new FileOutputStream(bcpFile);
ResultMap resultMap = new ResultMap();
System.out.println("创建文件开始CSV");
try {
bcpFileWriter.write(bom);
//获取业务数据
List<TestVo> testVoList = testService.selectTestInfo();
// 写入文件头部
String title = "\"表头一\",\"表头二\",\"表头三\"," +
"\"表头四\",\"表头五\",\"表头六\"";
bcpFileWriter.write((new String(title.getBytes(), "utf-8")).getBytes());
bcpFileWriter.write("\n".getBytes());
String str = "";
if(testVoList!=null && testVoList.size()>0){
String param = "";
for (int i = 0; i < testVoList.size(); i++) {
param = "\""+testVoList.get(i).getTest1()+"\","
+"\""+testVoList.get(i).getTest2()+"\","
+"\""+testVoList.get(i).getTest3()+"\","
+"\"\"," // 此行列设置为了空数据
+"\"\t"+testVoList.get(i).getTest5()+"\t\"," // \t可将单元格设置为文本格式
+"\""+testVoList.get(i).getTest6()+"\"\n";
str+=param;
}
}
bcpFileWriter.write(str.getBytes());
System.out.println("创建文件结束CSV");
} catch (Exception e) {
e.printStackTrace();
System.out.println("创建文件异常CSV");
}try {
bcpFileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
return resultMap;
}
自己开发过程中遇到的问题(你们大概率用不到):
我在开发过程中导出csv时往一个单元格塞数据是由于长度达到33000字符(查了资料一个单元格能塞32,767字符),导致在打开是发现自动换了行。但是在苹果电脑里打开是正常没有换行,导入也正常。可能就是显示的问题,没有细究过。你也可以用文本的方式打开看看,应该是没问题的。
版权声明:本文为m0_37310224原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。