问题描述:java页面导出的csv格式的表格,用excel打开有乱码,但是用记事本打开没有乱码能够正常显示。
问题代码:
ServletActionContext.getResponse().reset();// 清空输出流
ServletActionContext.getResponse().setHeader(
"Content-disposition",
"attachment; filename=" + Common.DateFormat(new Date(), "yyyy-MM-dd HH:mm:ss")
+ "ChannelIndicator.csv");// 设定输出文件头
ServletActionContext.getResponse().setContentType("application/csv");// 定义输出类型
HttpServletResponse response = ServletActionContext.getResponse();
// 设置字符集
response.setContentType("text/plain");// 设置输出为文字流
response.setCharacterEncoding("UTF-8");
PrintWriter pw = null;
try {
pw = response.getWriter();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
问题原因:excel默认按平台默认的字符集ANSI打开文件,也就是说在windows平台上excel默认用gb2312打开文件,所以出现了之前的问题。知道问题原因更改就比较容易啦。
修改后的代码:
ServletActionContext.getResponse().reset();// 清空输出流
ServletActionContext.getResponse().setHeader(
"Content-disposition",
"attachment; filename=" + Common.DateFormat(new Date(), "yyyy-MM-dd HH:mm:ss")
+ "ChannelIndicator.csv");// 设定输出文件头
ServletActionContext.getResponse().setContentType("application/csv");// 定义输出类型
// 在windows平台上导出的csv用excel导出是乱码,需要把字符集设置为gb2312
HttpServletResponse response = ServletActionContext.getResponse();
// 设置字符集
response.setContentType("text/plain");// 设置输出为文字流
response.setCharacterEncoding("gb2312");
PrintWriter pw = null;
try {
pw = response.getWriter();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}