2

我在 Nodejs 应用程序中使用了 exceljs npm 来生成我的预格式化数据的 excel 文件。

它按预期工作并下载excel文件。该文件正在除 MS Excel 2007 之外的所有软件中打开。它显示如下图所示的错误,如果我们按是,只需打开新工作表。错误在下面的屏幕截图中

在此处输入图像描述

我使用的代码如下。

exports.getDocExcel = function(req, res) {


  var workbook = new Excel.Workbook();

  var worksheet = workbook.addWorksheet('Manage_Customer');

  worksheet.columns = [{
      header: 'SoldTo_Customer',
      key: 'SoldTo_Customer',
      width: 20
    },
    {
      header: 'CDC_CustomerID',
      key: 'CDC_CustomerID',
      width: 20
    },
    {
      header: 'CDC_Name',
      key: 'CDC_Name',
      width: 20
    },
    {
      header: 'CDC_City',
      key: 'CDC_City',
      width: 20
    },
    {
      header: 'CDC_State',
      key: 'CDC_State',
      width: 20
    },
    {
      header: 'CDC_Zip',
      key: 'CDC_Zip',
      width: 20
    },



  ];

  var fileName = "sample.xlsx";
  var tempFilePath = __dirname + fileName;

  workbook.xlsx.writeFile(tempFilePath).then(function() {
    fs.readFile(tempFilePath, function(err, data) {
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
      res.write(data);
      res.end();
    });
  });

};

服务器页面如下

const express = require("express");
const app = express();
const bodyParser = require('body-parser');
const path = require('path');
const dotenv = require('dotenv');
const chalk = require('chalk');
const multipart = require("connect-multiparty");
var sql = require("mssql");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(express.static( __dirname + "/public"));
dotenv.load({ path: '.env.Config' });
app.set('port', process.env.App_PORT || 3000);
app.listen(app.get('port'), () => {
    console.log('%s server running on port', chalk.green('✓'), app.get('port'));
    console.log('  Press CTRL-C to stop\n');
});
const pdfController = require('./public/controllers/pdf.js');
app.get("/doc-to-excel",pdfController.getDocExcel);

如何解决这个问题?

4

0 回答 0