node-xlsx导出excel文件流,前端axios实现下载excel
程序员文章站
2022-05-30 15:04:17
...
服务端:
1.node-xlsx的安装npm install node-xlsx --save
2.单独抽出一个文件 写导表的逻辑
附:https://www.npmjs.com/package/node-xlsx npm文档
const xlsx = require("node-xlsx"); //引入模块
const exportExcel = (data) => {
// 設置表格列寬
const options = {
"!cols": [
{ wch: 25 },
{ wch: 45 },
{ wch: 90 },
{ wch: 20 },
{ wch: 20 },
{ wch: 90 },
],
};
// 要導出的數據數組
let xlsxObj = [
{
name: "sheet",
data: [
// [
// "食品組別",
// "食品名稱",
// "食品短描述",
// "食品金額",
// "食品原價",
// "食品圖片",
// ],
[
"Parent_ID",
"FOOD_NAME1",
"FOOD_DESC",
"PRICE",
"MARKET_PRICE",
"Image_URL",
],
],
},
];
// 生成導出的數據
let foodData = data;
foodData.forEach((item) => {
let typeArr = [];
typeArr.push(item.type);
item.foodsList.forEach((list) => {
let listArr = [];
for (const key in list) {
listArr.push(list[key]);
}
xlsxObj[0].data.push(typeArr.concat(listArr));
});
});
//xlsxObj最终的数据格式为:
// 二维数组
// [
// ["Parent_ID","FOOD_NAME1","FOOD_DESC","PRICE","MARKET_PRICE","Image_URL"],//第一列为表头信息
// ['第一行第一列内容','第一行第二列内容','第一行第三列内容',......],
// ['第二行第一列内容','第三行第二列内容','第二行第三列内容',......],
// ......
// ]
return xlsx.build(xlsxObj, options)
};
module.exports = exportExcel;
3.后端路由 部分
// 导出excel文件
const exportExcel = require('./modules/exportExcel');
// excel導出接口
app.post('/nodexls', (req, res) => {
// 設置響應頭
res.setHeader('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
//if判断这一段可以不需要 是我在写爬虫获取的时候 保存了一个文本信息到global中 用来导出对应页面 名称excel文件名用的
// encodeURIComponent()方法用来处理 中文文件名 防止乱码 如果是导出文件名为英文名 可以不需要
if (global.restaurant) {
res.setHeader("Content-Disposition", "attachment; filename=" + encodeURIComponent(global.restaurant) + ".xlsx");
} else {
res.setHeader("Content-Disposition", "attachment; filename=" + encodeURIComponent("食物商品信息") + ".xlsx");
}
//最终返回excel二进制文件流
res.end(exportExcel(global.foodData), 'binary');
})
前端页面:
exportExcel() {
//post 的请求头一定要加 { responseType: 'arraybuffer' }
//不然导出的excel文件会提示损坏 或者 乱码
axios.post('/nodexls', {}, { responseType: 'arraybuffer' }).then(response => {
const blob = new Blob([response.data],
{
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
})
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = `${this.restaurantName}.xlsx`;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
})
}
下一篇: DeFi千呼万唤,AC交易公链始出
推荐阅读
-
java实现导出文字+数据的excel文件并返回文件流
-
亲测可用!微信小程序实现下载预览文件,导出及保存文件及excel
-
亲测可用!微信小程序实现下载预览文件,导出及保存文件及excel(2)
-
Vue前端导出Excel文件的详细实现方案
-
前端axios下载excel文件(二进制)的处理方法
-
vue项目中导出Excel文件功能的前端代码实现
-
node-xlsx导出excel文件流,前端axios实现下载excel
-
php导出下载Excel文件被IE阻止,如何解决?用流输出也不行
-
原生PHP实现导出csv格式Excel文件的方法示例【附源码下载】
-
java实现导出文字+数据的excel文件并返回文件流