React+Ant Design实现导出excel表格文件显示损坏打不开解决办法
简单描述一下最近实现的一个小小的功能需求,以便后期有用。同时期待与大家一起交流学习。
1,需求:在react项目中,调用后台数据,在table中展示数据。
点击一个导出按钮,实现单选,多选导出单条,单张,多张表数据。
2,解决方法其一:前端方法调用后台接口实现导出。
3,关键代码:
exportExcel= (ip, Statu) =>{
var selectedRows= this.state.selectedRows
if(selectedRows.length!=0){
this.props.cmdbStore.exportExcelByList(selectedRows).then(response => {
var blob = new Blob([this.props.cmdbStore.exportExcelByLists], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = objectUrl;
a.download = '单选多选表数据.xlsx';
a.click();
document.body.removeChild(a);
})
}else{
var code = {ip:"",Statu:""}
this.props.cmdbStore.exportExcel(code).then(response => {
var blob = new Blob([this.props.cmdbStore.exportExcels], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = objectUrl;
a.download = '所有表数据.xlsx';
a.click();
document.body.removeChild(a);
})
}
}
4,问题及解决
问题:前端调用后端接口后,已经实现导出功能,但是下载下来的excel显示文件损坏打不开。
方法:在axios请求接口中添加:
"responseType": 'blob'
5,着重要点及开发意义:
找错定位必须清晰,操作一步到位。