现时需要开发一个Excel下载功能
后台有一个API,负责接收传入的JSON文件,生成带图片的Excel文件在临时目录(生成Excel使用npm exceljs库),并将文件通过Router返回
前台Client调用后台API,读取文件流生成Excel文件下载
API生成Excel文件代码
const getLinePlanExcelJson = (data) => {'col' + headerIndex,
// let workBook;
//workbook properties
var workBook = new exceljs.Workbook();
workBook.creator = 'Esquel LPD Project';
workBook.lastModifiedBy = 'Esquel LPD Project';
workBook.created = new Date();
workBook.modified = new Date();
return new Promise((resolve, reject) => {
if (typeof (data.customerCode) === 'undefined' || typeof (data.linePlanProducts) === 'undefined') {
reject(new Error('{"Error Message":"incorrect format."}'));
}
//base var
let mc_productStyles = data.productStyles;
let mc_productFabrics = data.productFabrics;
let mc_productTrims = data.productTrims;
//---------------------------
let workSheet_name = "LinePlan";
// create worksheet
let workSheet = workBook.addWorksheet(workSheet_name, {
// properties: {
// tabColor: { argb: 'FFC0000' }
// },
// pageSetup: {
// paperSize: 50,
// orientation: 'landscape'
// }
});
//setting header title
let headerTitleArray = config.LinePlan.columns;
let headerColumns = [];
for (let headerIndex = 0; headerIndex ) {
headerColumns.push({
header: headerTitleArray[headerIndex].title,
key:
API路由代码
let express = require('express');View Code
let genCSV = require("./genCSV.js");
let exceljs = require('exceljs');
let util = require('util');
let fs = require('fs');
let router = express.Router();
//post data to router
router.post('/', function (req, res, next) {
genCSV.getLinePlanExcelJson(req.body)
.then((excelObject) => {
// throw new Error('this is test error');
//return to client
let fileName = 'LinePlan-' + req.body.linePlanID + '.xlsx';
let filePath = './public/temp/' + fileName;
if (fs.existsSync(filePath)) {
fs.unlink(filePath);
}
excelObject.xlsx.writeFile(filePath, { bookType: 'xlsx', bookSST: false, type: 'buffer' })
.then(() => {
res.status(200).download(filePath, fileName);
}).catch((err) => {
throw err
});
})
.catch((err) => {
res.status(500).end('{"err":"' + err.message + '"}');
});
});
module.exports = router;
前台Client调用代码
fetchMethodExcel: function (apiName, method, requestObject, requestBody, callback) {View Code
fetch3(this.apiExport(apiName, requestObject), {
// method: method,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody),
})
.then((data) => {
if (data.status === 500) {
throw new Error('Explort LinePlan API Error');
} else if (data.status === 404) {
throw new Error('Can Not Found Explort LinePlan API');
}
return data.blob();
})
.then((blob) => {
let a = document.createElement('a');
let url = window.URL.createObjectURL(blob);
let filename = 'LinePlan-' + requestBody.linePlanID + '.xlsx';
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
callback();
})
.catch(err => {
callback(err);
});
}
运行结果是
但是下载的文件却是无法打开的,一直说是文件有内容有问题,尝试恢复很久都没有返回。
解除锁定后,可以正常打开文件了