问题描述
给自己的web系统写了个导出表格excel文件的代码,用到是ajax请求post方法的接口,返回后对其response保存为xls文件,但是保存后一直是乱码的,显示格式错误,使用postman测试了导出接口,发现是没有问题的,直接send and download可以下载正确的xls文件
源代码
js部分 请求接口,创建url,下载
这个代码是网上抄过来改的,确实能post触发下载,也下载到了文件,就是文件格式不太对劲
$.ajax({
type: 'post',
url: window.BASE_URL + window.paths.userListXls,
data: JSON.stringify({
filtrate: {
limit,
offset,
...filtrate
},
dictionary,
sheetName: sheetName,
}),
contentType: "application/json;charset=UTF-8",
responseType: 'blob'
}).then((res, statusTest, xhr) = >{
window.xhrr = xhr;
console.log(xhr, res == xhr.responseText) let disposition = xhr.getResponseHeader("Content-Disposition");
let fileName = disposition.slice(disposition.indexOf("fileName=") + 9);
const blob = new Blob([res], {
type: "application/vnd.ms-excel;charset=utf-8"
});
// 创建一个超链接,将文件流赋进去,然后实现这个超链接的单击事件
const elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
})
java后台
@RequestMapping(value = "/xls/export", method = RequestMethod.POST)
public @ResponseBody
String excelExportHandle(HttpServletRequest req, HttpServletResponse res) {
try {
ExportGuide guide = (ExportGuide) req.getAttribute("guide");
// 数据
JSONArray data = (JSONArray) req.getAttribute("data");
ServletOutputStream out = res.getOutputStream();
try {
res.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(guide.getFileName() + guide.getType().getSuffix(), "UTF-8"));
res.setContentType("application/vnd.ms-excel;charset=utf-8");
} catch(UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 数据转换成workbook
Workbook workbook = ExcelUtils.listToXls(guide.getFileName(), data, ExcelUtils.getDictionary(guide.getDictionary()), guide.isHasHeader());
workbook.write(out);
out.flush();
out.close();
return null;
} catch(Exception e) {
e.printStackTrace();
return "fail";
}
}