后端
public class EasyExcelUtil {
//导出Excel
public void exproExcel(HttpServletResponse response, List<?> data, String fileName, String sheetName, Class<? extends BaseRowModel> cls){
try {
response.reset();
OutputStream output = response.getOutputStream();
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
EasyExcel.write(bufferedOutput)
.head(cls)
.autoCloseStream(true)
.excelType(ExcelTypeEnum.XLSX)
.sheet(sheetName)
.doWrite(data);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
response.setHeader("Access-Control-Expose-Headers","FileName");
response.setHeader("FileName",URLEncoder.encode(fileName,"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
前端
//封装请求
function getDownload() {
// xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var customerId = self.customerId;
let day = moment().format('YYYY-MM-DD');
const token = getValueFromLocalStorage("token");
const url = cb.router.HTTP_CHECK_INFO+"?customerId="+customerId+"&day="+day;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.responseType = "blob";
xhr.setRequestHeader("token",token);
// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
xhr.onload = function () {
// 请求完成
if (this.status === 200) {
var data = this.response;
const fileName = "对账申请单.xlsx";
//解决乱码问题
const blob = new Blob(["\uFEFF",data],{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
// const blob = new Blob([data]);
// 创建一个a标签用于下载
console.log(blob);
var a = document.createElement('a');
let objectUrl = window.URL.createObjectURL(data)
a.href = objectUrl;
a.download = fileName;
a.style.display = 'none';
a.setAttribute('download',fileName);
//启动a标签点击事件下载
a.click();
$(a).remove(); // 下载完成移除元素
window.URL.revokeObjectURL(objectUrl) // 释放掉blob对象
}
};
// 发送ajax请求
xhr.send()
}
上面代码没有任何问题在导出Ecxel的时候出现乱码问题
QQ图片20201117104536.jpg
排查问题最后找到是因为mock.js文件原因,每次执行这个JS文件会拦截请求,造成乱码的情况注释掉就好了(你奶奶个腿)
QQ图片20201117104628.png
QQ图片20201117104840.png
恢复正常~