1、后端代码spring cloud项目
@RequestMapping("/printexcel")
@ResponseBody
public void printSaleInvoiceToExcel( HttpServletResponse response) throws ParseException {
// 查询数据,生成Excel返回byte数组
byte[] databyte = saleInvoiceCustomsExcelService.saleInvoiceExportExcel(new Context());
OutputStream out = null;
try {
//重点:要写对类型,要不然下载文件打不开
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
out = response.getOutputStream();
out.write(databyte);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(out!=null) out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2、nuxt vue前端写法,后面有时间再优化改进
var _this = this;
var query = _this.query;
_this.loadingFlag = true;
_this.$axios.post("/printexcel", { query: query }, { responseType: "arraybuffer" }).then((result) => {
var blob = new Blob([result], {
type: "application/vnd.ms-excel;charset=utf-8"
});
var downloadElement = document.createElement("a");
var href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.style.display = "none";
downloadElement.href = href;
downloadElement.download = "allProcurementPlanInfo.xlsx"; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
_this.loadingFlag = false;
}).catch(() => {
this.$message({
type: 'info',
message: 'download canceled'
});
_this.loadingFlag = false;
});
3、对照部分截图
详情看下面的连接,暂时没有时间去找官网
https://www.runoob.com/http/mime-types.html
参考文章:https://blog.csdn.net/qweasdassd/article/details/122553718