尝试下载在 Nodejs 中创建的 Excel 文件时"Http failure during parsing" (ExcelJS)



我正在尝试将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

var tempfile = require('tempfile');
var tempFilePath = tempfile('.xlsx');
console.log("tempFilePath : ", tempFilePath);
workbook.xlsx.writeFile(tempFilePath).then(function() 
{
res.sendFile(tempFilePath, function(err)
{
if (err)
{
console.log('---------- error downloading file: ', err);
}
});
console.log('file is written');
});
}
}

这是在客户端中接近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
);    
}

你需要告诉 Angular 它可以期待什么类型的响应,以便您可以添加

响应类型

到您的 HTTP 选项:

getExcel(request : any , reportName : string ) : Observable<any>
{
var path = <relevant path to the nodejs endpoint>;
const options = { withCredentials: true, responseType: 'blob' };
return this.http.post<any>(path, {request: request, reportName : reportName }, options) //This route to the getDataByPromise function
}

找到了一个解决方案 - 我使用了错误的方法:我没有使用带有承诺的 writeFile,然后使用 res.sendFile - 我将响应的标头设置为"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"内容类型和"内容处置"、"附件;文件名=投票框.xlsx",然后 使用发送工作簿"写入"方法的响应发送 - 请参阅更正的代码:

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();
})

我也会在代码中更正它

相关内容

最新更新