Java Web响应csv文件设置
方案1(使用GBK)
代码
String filename = "掃描全能王" + System.currentTimeMillis() + ".csv";
// 支持文件名带繁体字
byte[] fileNameByte = (filename ).getBytes("UTF-8");
String filename = new String(fileNameByte, "ISO8859-1");
// 弹出对话框让用户下载
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
OutputStream out = null;
BufferedWriter writer= null;
// 设置响应内容,gbk支持繁体字,gb2312不支持
response.setContentType("application/csv;charset=GBK");
response.setCharacterEncoding("GBK");
try {
out = response.getOutputStream();
writer= new BufferedWriter(new OutputStreamWriter(out, "GB2312"), 1024);
// 写入文件内容
....
writer.flush();
} catch (Exception e) {
log.error("导出异常:{} {}", e.getMessage(), e);
} finally {
// writer\out 流关闭
try {
if(writer!= null) {
writer.close();
}
} catch (IOException e) {
log.warn("close stream csvWtriter error!");
}
try{
if(out != null){
out.close();
}
}catch (IOException e){
log.warn("close stream out error!");
}
}
缺点
- 谷歌、火狐、360等主流浏览器没问题,但ie11下载时文件名出现乱码。
- 不支持韩文、维吾尔文等。
方案2(utf-8)
代码
String filename = "掃描全能王" + System.currentTimeMillis() + ".csv";
String agent = request.getHeader("User-Agent").toUpperCase(); // 浏览器信息
if (agent.indexOf("MSIE") > 0 || (agent.indexOf("GECKO")>0 && agent.indexOf("RV:11")>0)) { //IE浏览器和Edge浏览器
filename = URLEncoder.encode(filename, "UTF-8");
} else { //其他浏览器
filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
}
// 弹出对话框让用户下载
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
OutputStream out = null;
BufferedWriter writer= null;
try {
out = response.getOutputStream();
writer= new BufferedWriter(new OutputStreamWriter(out, "UTF-8"), 1024);
// 写入文件内容
....
writer.flush();
} catch (Exception e) {
log.error("导出异常:{} {}", e.getMessage(), e);
} finally {
// writer\out 流关闭
}
优缺点
优点
- 文件名再谷歌、火狐、360、ie11、edge等浏览器上均无乱码问题;
- 文件内容支持繁体、维吾尔文、韩文等,均不会有乱码问题;
缺点
office excel打开有乱码;
相关知识
Content-Disposition属性有两种类型
- inline :将文件内容直接显示在页面
- attachment:弹出对话框让用户下载
几种编码类型说明
参考:https://blog.youkuaiyun.com/jhj_666/article/details/77940872
GBK: 汉字国标扩展码,基本上采用了原来GB2312-80所有的汉字及码位,并涵盖了原Unicode中所有的汉字20902,总共收录了883个符号, 21003个汉字及提供了1894个造字码位。 Microsoft简体版中文Windows 95就是以GBK为内码,又由于GBK同时也涵盖了Unicode所有CJK汉字,所以也可以和Unicode做一一对应。
GB码,全称是GB2312-80《信息交换用汉字编码字符集 基本集》,1980年发布,是中文信息处理的国家标准,在大陆及海外使用简体中文的地区(如新加坡等)是强制使用的唯一中文编码。P-Windows3.2和苹果OS就是以GB2312为基本汉字编码, Windows 95/98则以GBK为基本汉字编码、但兼容支持GB2312。GB码共收录6763个简体汉字、682个符号,其中汉字部分:一级字3755,以拼音排序,二级字3008,以偏旁排序。该标准的制定和应用为规范、推动中文信息化进程起了很大作用。
GBK编码是中国大陆制订的、等同于UCS的新的中文编码扩展国家标准。GBK工作小组于1995年10月,同年12月完成GBK规范。该编码标准兼容GB2312,共收录汉字21003个、符号883个,并提供1894个造字码位,简、繁体字融于一库。