今天遇到了一个问题,在导出excl时,文件下载出现了文件名乱码的问题。
出错的代码如下:
/**
* 下载文件
*
* @param response
* @param fileName 导出文件名
* @param workbook 导出excel对象
* @return
* @author 刘朋
* <br/>date 2019-08-01
*/
public static void export(HttpServletResponse response, String fileName, Workbook workbook) throws IOException {
if (workbook != null) {
fileName = new String(fileName.getBytes(CHAR_ENCODING), HTML_CHAR_ENCODING);
//设置响应头格式
String headStr = "attachment; filename=\"" + fileName + "\"";
//设置响应的内容类型
response.setContentType("APPLICATION/OCTET-STREAM");
//Content-Disposition响应头
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream();
workbook.write(out);
}
}
此代码会导致在IE浏览器上运行乱码,chrome上则没有问题。
后来将代码修改后则解决了此问题,修改后的代码如下:
/**
* 下载文件
*
* @param response
* @param fileName 导出文件名
* @param workbook 导出excel对象
* @return
* @author 刘朋
* <br/>date 2019-08-01
*/
public static void export(HttpServletResponse response, String fileName, Workbook workbook) throws IOException {
if (workbook != null) {
// fileName = new String(fileName.getBytes(CHAR_ENCODING), HTML_CHAR_ENCODING);
//设置响应头格式
String headStr = "attachment; filename="+ Encodes.urlEncode(fileName);
//设置响应的内容类型
response.setContentType("application/force-download");
//Content-Disposition响应头
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream();
workbook.write(out);
}
}
public static String urlEncode(String part) {
try {
return URLEncoder.encode(part, "UTF-8");
} catch (UnsupportedEncodingException var2) {
throw Exceptions.unchecked(var2);
}
}