如何迭代行并在节点js中打印excel中的对象值?

时间:2018-04-26 10:54:06

标签: node.js excel express excel4node

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

[
    {   "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中打印对象的数据?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

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

Excel行从行1开始,您的数组是索引0,因此您需要确保在写入Excel时始终以1开头,或者在您的情况下从自从您创建了标题行以来的行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!'))