alibaba / easyexcel

快速、简洁、解决大文件内存溢出的java处理Excel工具
https://easyexcel.opensource.alibaba.com
Apache License 2.0
32.05k stars 7.5k forks source link

如何生成一个带有BOM头的csv文件 #4006

Open FristDawn opened 3 hours ago

FristDawn commented 3 hours ago

public static Pair<ExcelWriter, WriteSheet> buildCsvWriter(File file, String sheetName, Charset charset) { ExcelWriter excelWriter = EasyExcel.write(file).charset(charset).build(); WriteSheet writeSheet = new WriteSheet(); writeSheet.setSheetName(sheetName);

    return Pair.of(excelWriter, writeSheet);
}

再生成文件写入句柄的时候,设置了utf-8编码格式,但是生成文件无法带bom头, tempFile = File.createTempFile(SESSION_DETAIL_FILE_NAME + System.currentTimeMillis(), ".csv",dir); fos = new FileOutputStream(tempFile.getPath()); fos.write(new byte[]{(byte)0xEF, (byte)0xBB, (byte)0xBF}); fos.flush(); 在获取句柄前单独写入也不行 会话明细17272333965255218563994055952976.csv: Unicode text, UTF-8 text, with CRLF line terminators

所以我该如何生成一个带有bom头的csv文件呢?

imgoby commented 2 hours ago
   try(OutputStream os = response.getOutputStream()){

        String filename = "export.csv";
        response.setHeader("Content-Disposition", "attachment;fileName=" + filename);

        //写bom,解决微软Excel乱码。
        byte[] bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
        os.write(bom);

        FileUtils.copyFile(file1, os);

}catch(Exception e){

}