linux服务器上下载的csv文件在window环境下用excel打开的乱码问题解决
2018-04-09 14:39
1006 查看
【问题产生原因】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();
}
}
}
【核心代码】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
相关文章推荐
- linux服务器上下载的csv文件在window环境下用excel打开的乱码问题解决
- java输出utf-8的csv文件时,文件中有中文,excel打开文件乱码问题解决
- Java IO流将数据输出到.csv文件中,excel打开时乱码问题的解决
- 记事本能正常打开的csv文件,用Excel打开乱码问题解决办法
- 解决csv文件用excel打开乱码的问题
- Excel打开csv文件乱码问题的解决办法
- 解决PHP生成UTF-8编码的CSV文件用Excel打开乱码的问题
- 解决PHP文件(word/excel)下载 内容打开乱码问题
- 如何解决PHP生成UTF-8编码的CSV文件用Excel打开乱码的问题
- 解决PHP生成UTF-8编码的CSV文件用Excel打开乱码的问题
- java 以utf-8生成csv文件,用excel打开乱码问题解决
- 如何解决.csv格式文件用excel打开是乱码的问题?
- [置顶] 解决PHP生成UTF-8编码的CSV文件用Excel打开乱码的问题
- PHP 用fputcsv()生成csv文件在windows Excel 下打开乱码问题解决
- 解决PHP生成UTF-8编码的CSV文件用Excel打开乱码的问题
- 解决Excel打开UTF-8编码的CSV文件乱码的问题 推荐
- 解决Excel打开UTF-8编码CSV文件乱码的问题
- Excel打开csv文件乱码问题的解决办法
- 生成csv文件时,2010微软excel打开乱码解决
- 解决 Excel 打开 UTF-8 编码 CSV 文件乱码的 BUG