利用ajax实现excel报表导出【解决乱码问题】,供大家参考,具体内容如下
背景
项目中遇到一个场景,要导出一个excel报表。由于需要token验证,所以不能用a标签;由于页面复杂,所以不能使用表单提交。初步考虑前端使用ajax,后端返回流,定义指定的header。
第一版
主要代码
前端
使用jquery的ajax
var queryparams = {"test":"xxx"};
var url = "xxx";
$.ajax({
type : "post", //提交方式
url : url,//路径
contenttype: "application/json",
data: json.stringify(queryparams),
beforesend: function (request) {
request.setrequestheader("authorization", "xxx");
},
success : function(result) {
const blob = new blob([result], {type:"application/vnd.ms-excel"});
if(blob.size < 1) {
alert('导出失败,导出的内容为空!');
return
}
if(window.navigator.mssaveoropenblob) {
navigator.mssaveoropenblob(blob, 'test.xls')
} else {
const alink = document.createelement('a');
alink.style.display = 'none';
alink.href = window.url.createobjecturl(blob);
alink.download = 'test.xls';
document.body.appendchild(alink);
alink.click();
document.body.removechild(alink);
}
}
});
后端
使用easypoi(如何使用easypoi请自行百度)
import cn.afterturn.easypoi.excel.excelexportutil;
import cn.afterturn.easypoi.excel.entity.exportparams;
@postmapping(value = "/download")
public void downloadlist(@requestbody objct obj, httpservletresponse response) {
......
list<custom> excellist = new arraylist<>();
// excel总体设置
exportparams exportparams = new exportparams();
// 指定sheet名字
exportparams.setsheetname("test");
workbook workbook = excelexportutil.exportexcel(exportparams, custom.class, excellist);
response.setcontenttype("application/vnd.ms-excel");
response.addheader("content-disposition", "attachment;filename=" + urlencoder.encode("test", "utf-8") + ".xls");
outputstream outputstream = response.getoutputstream();
workbook.write(outputstream);
outputstream.flush();
outputstream.close();
......
}
测试结果
excel能正常导出,但下载下来的excel全是乱码。经过各种找答案,整理了一下可能是以下原因导致:
1、后端未设置字符集,或者在spring框架的过滤器中统一设置了字符集;
2、前端页面未设置字符集编码;
3、需要在ajax中添加 request.responsetype = “arraybuffer”;
经过不断测试,我的应该是第三点导致。但在jquery ajax 中添加后仍然不起作用,乱码问题始终无法解决。
第二版
主要代码
前端,使用原生的ajax。后端未变动。
var xhr = new xmlhttprequest();
xhr.responsetype = "arraybuffer";
xhr.open("post", url, true);
xhr.onload = function () {
const blob = new blob([this.response], {type:"application/vnd.ms-excel"});
if(blob.size < 1) {
alert('导出失败,导出的内容为空!');
return;
}
if(window.navigator.mssaveoropenblob) {
navigator.mssaveoropenblob(blob, 'test.xls')
} else {
const alink = document.createelement('a');
alink.style.display = 'none';
alink.href = window.url.createobjecturl(blob);
alink.download = 'testxls';
document.body.appendchild(alink);
alink.click();
document.body.removechild(alink);
return;
}
}
xhr.setrequestheader("authorization", "xxx");
xhr.setrequestheader("content-type", "application/json");
xhr.send(json.stringify(queryparams));
测试结果
下载的excel不再乱码,原生ajax中使用 “arraybuffer” 使用是生效的。
总结
“arraybuffer” 这个参数导致的excel导出乱码,在原生的ajax中设置是有效的,在jquery的ajax中暂时还没找到生效的方式。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持代码网。
发表评论