尝试下载在nodejs(exceljs)中创建的excel文件时,出现“解析期间Http失败”

dced5bon  于 2023-03-01  发布在  Node.js
关注(0)|答案(2)|浏览(191)

我正在尝试将在nodejs中创建的xls文件下载到客户端(使用exceljs)。
由于某种原因-我无法在客户端保存文件-我在订阅getExcel可观察对象时收到“Http failure during parsing for“。我是否缺少一些头文件定义?请参阅我的代码:
这是nodej端:

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

zbsbpyhn1#

您需要告诉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
}
b91juud3

b91juud32#

找到了解决方案-我使用了错误的方法:我没有使用带有promise的writeFile和res.sendFile,而是将响应的头设置为“application/vnd. openxmlformats-offedocument.spreadsheetml.sheet”内容类型和“Content-Disposition”,“attachment”;filename=votingboxes.xlsx”,然后使用发送工作簿的响应“write”方法发送-请参见更正的代码:

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

我也会在代码中更正它

相关问题