linux服务器上下载的csv文件在window环境下用excel打开的乱码问题解决

【问题产生原因】

Excel默认并不是以UTF-8来打开文件,所以在csv开头加入BOM,告诉Excel文件使用utf-8的编码方式。

【核心代码】

response.setContentType("application/force-download;charset=utf-8");// 设置强制下载不打开
response.addHeader("Content-Disposition",
        "attachment;fileName=" + fileName);// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
    fis = new FileInputStream(file);
    bis = new BufferedInputStream(fis);
    OutputStream os = response.getOutputStream();
    // 加上bom头,才不会中文乱码  -- window上不用加,linux上必须加上才行
    os.write(new   byte []{( byte ) 0xEF ,( byte ) 0xBB ,( byte ) 0xBF });
    int i = bis.read(buffer);
    while (i != -1) {
        os.write(buffer, 0, i);
        i = bis.read(buffer);
    }

    System.out.println("success");
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (bis != null) {
        try {
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (fis != null) {
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
文章来源:https://blog.csdn.net/HAHA362/article/details/74179744

猜你喜欢

转载自blog.csdn.net/qq_34464926/article/details/79866244
今日推荐