java csv文件导出UTF-8乱码解决方案

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字符),导致在打开是发现自动换了行。但是在苹果电脑里打开是正常没有换行,导入也正常。可能就是显示的问题,没有细究过。你也可以用文本的方式打开看看,应该是没问题的。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值