Java在实现导出时,可设置响应头的内容,来设置响应的编码格式、响应类型、以及中文乱码问题等
public static HttpServletResponse setResponse(HttpServletResponse response, String fileName, String fileType) {
if (StringUtils.isBlank(fileName)) {
throw new RuntimeException("请设置导出的文件名");
}
// 设置响应类型
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// 设置编码格式
response.setCharacterEncoding("UTF-8");
// 设置URLEncoder.encode 防止中文乱码
try {
fileName = URLEncoder.encode(fileName, "UTF-8").replace("\\+", "%20");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// 设置响应头
// 1、下面请求头 浏览器下载正常,但是postman下载文件名称乱码
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + fileType);
// response.setHeader("Content-disposition", "attachment;filename=utf-8" + fileName + ".xlsx");
return response;
}