【发布时间】:2019-09-04 11:54:21
【问题描述】:
我正在尝试将在 nodejs 中创建的 xls 文件下载到客户端(使用 exceljs)。 创建基于http://www.ihamvic.com/2018/07/25/create-and-download-excel-file-in-node-js/
由于某种原因 - 我无法在客户端中保存文件 - 我在订阅 getExcel 可观察对象时收到“解析期间的 Http 失败”。 我错过了一些标题定义吗? 查看我的代码:
这是nodejs端:
const express = require('express');
const router = express.Router();
const excel = require('./excel');
router.use(req, res, next) =>
{
//The getDataByPromise is a function that return a promise
return getDataByPromise(req.body.request).then((dataResult) => {
let reportName = req.body.reportName ? req.body.reportName : '';
return excel.createExcel(res, dataResult, reportName);
}).catch((err) => {
next({
details: err
})
});
})
module.exports = router;
这是带有createExcel功能的excel模块:
module.exports =
{
createExcel : function(res, dataResult, reportTypeName)
{
let workbook = new excel.Workbook();
let worksheet = workbook.addWorksheet('sheet1');
dataResult.forEach(dataItem => worksheet.addRow(dataItem)); //Insert data into the excel
//SOLUTION - SOLVED
res.setHeader('Content-Type', 'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet');
res.setHeader("Content-Disposition", "attachment;
filename=votingboxes.xlsx");
workbook.xlsx.write(res).then(() =>
{
res.end();
})
}
这是在客户端接近 nodejs(我们称之为 srv)的服务:
getExcel(request : any , reportName : string ) : Observable<any>
{
var path = <relevant path to the nodejs endpoint>;
const options = { withCredentials: true };
return this.http.post<any>(path, {request: request, reportName : reportName }, options) //This route to the getDataByPromise function
}
这是组件函数:
exportToExcel() : void
{
this.srv.getExcel(votingBoxRequestForExcel, this.reportTypeNameForExcel).subscribe(result =>
{
const data: Blob = new Blob([result], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'});
//FileSaver is file-saver package
FileSaver.saveAs(data, 'test.xlsx');
},
error => console.log(error) //Reaching to the error instead of the response
);
}
【问题讨论】:
标签: node.js angular express filesaver.js exceljs