1

我有一个对象数组,如下所示:

[
    {   "FirstName": "John", 
        "LastName": "Parker", 
        "Age": "23", 
        "Cat": "23g",
        "SOP": "Active"
    },
    {   "FirstName": "Rose", 
        "LastName": "Jackson", 
        "Age": "44", 
        "Cat": "44g",
        "SOP": "InActive"
    }
]

我正在使用excel4node创建对象的数据并将其写入 excel

async generateExclReport(req, res) {
        try {

            var wb = new xl.Workbook();

            // Add Worksheets to the workbook
            var ws = wb.addWorksheet('Report');

            ws.cell(1, 1).string('FirstName');
            ws.cell(1, 2).string('LastName');
            ws.cell(1, 3).string('Age');
            ws.cell(1, 4).string('Cat');
            ws.cell(1, 5).string('SOP');


            var fileName = "Report" + Date.now().toString() + '.xlsx';

            res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            wb.write(fileName, res);
        } catch (err) {
            this.handleError(res, err);
        }    
    }

我可以在 excel 中打印标题并下载,但是如何在 excel 中打印对象的数据?

非常感谢任何帮助。

4

1 回答 1

6

您可以遍历数据并确保跳过您创建的标题行。

Excel 行从行开始,1您的数组是索引0,因此您需要确保1在写入 Excel 时始终从行开始,或者在您的情况下从行开始,2因为您创建了标题行(这就是您会看到的原因ws.cell(i + 2, 1).string(data[i].FirstName);)。

这是一个示例快递应用程序:

依赖项

npm install express
npm install excel4node

代码

const express = require('express');
const xl = require('excel4node');

const app = express();

app.get('/', (req, res) => {
  try {
    const data = [
      {   "FirstName": "John", 
          "LastName": "Parker", 
          "Age": "23", 
          "Cat": "23g",
          "SOP": "Active"
      },
      {   "FirstName": "Rose", 
          "LastName": "Jackson", 
          "Age": "44", 
          "Cat": "44g",
          "SOP": "InActive"
      }
    ];

    const wb = new xl.Workbook();

    // Add Worksheets to the workbook
    const ws = wb.addWorksheet('Report');

    ws.cell(1, 1).string('FirstName');
    ws.cell(1, 2).string('LastName');
    ws.cell(1, 3).string('Age');
    ws.cell(1, 4).string('Cat');
    ws.cell(1, 5).string('SOP');

    for (let i = 0; i < data.length; i += 1) {
      ws.cell(i + 2, 1).string(data[i].FirstName);
      ws.cell(i + 2, 2).string(data[i].LastName);
      ws.cell(i + 2, 3).string(data[i].Age);
      ws.cell(i + 2, 4).string(data[i].Cat);
      ws.cell(i + 2, 5).string(data[i].SOP);
    }

    const fileName = `Report_${Date.now().toString()}.xlsx`;

    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    wb.write(fileName, res);

  } catch (err) {
      console.error(res, err);
  }
});

app.listen(3000, () => console.log('Example app listening on port 3000!'))
于 2018-04-26T11:31:59.093 回答