使用节点xlsx动态创建列

时间:2017-05-01 21:32:31

标签: javascript node.js excel npm xlsx

我尝试使用npm xlsx提供的数据创建一个excel文件。 https://www.npmjs.com/package/xlsx

const players = [
    {
        "number": "34",
        "firstName": "Nate",
        "lastName": "Cole",
        "position": "Pitcher"
    },
    {
        "number": "5",
        "firstName": "Kyle",
        "lastName": "Carroll",
        "position": "Pitcher"
    }
];

以下是我选择要使用的列标题。

let worksheetColumns = [];

_.forEach(players, function (object) {
    _.forEach(object, function (value, key) {
        worksheetColumns.push(key);
    });
});

const uniqueColumns = _.uniq(worksheetColumns);

我可以对列和行进行硬编码,但我希望键是列标题,值是数据行。

const workbook = {
    SheetNames: ["Test Sheet"],
    Sheets: {
        "Test Sheet": {
            "!ref":"A1:Z5",
            A1: { t:'s', v: "column" },
            A2: { t:'s', v: "row" }
        }
    }
};

const wopts = { bookType:'xlsx', bookSST:false, type:'binary' };

XLSX.writeFile(workbook, 'output.xlsx', wopts);

1 个答案:

答案 0 :(得分:1)

您可以使用exceljs创建xls并动态处理新列。首先,如下创建工作簿实例

var workbook = new Excel.Workbook();

然后在工作簿中创建工作表

workbook.creator = "Me";
workbook.lastModifiedBy = "";
workbook.created = new Date();
workbook.modified = new Date();
workbook.lastPrinted = new Date();
workbook.properties.date1904 = true;
workbook.views = [
  {
    x: 0,
    y: 0,
    width: 10000,
    height: 20000,
    firstSheet: 0,
    activeTab: 1,
    visibility: "visible",
  },
];
var worksheet = workbook.addWorksheet("My Sheet");

然后在A1列创建一个表

worksheet.addTable({
name: "MyTable",
ref: "A1",
headerRow: true,
totalsRow: false,
style: {
    theme: null,
    showRowStripes: true,
    showColumnStripes: true,
},
columns: [
    { name: "EmployeeID" },
    { name: "First Name" },
 ],
 rows: [/* Enter initial rows if you want to add*/],
});

现在您可以动态添加列

const table = worksheet.getTable("MyTable");
table.addColumn({
    name: "Column name",
});
table.commit();