用nodeJs覆盖excel文件

时间:2015-08-05 17:27:44

标签: node.js sails.js

我想用sailsJs覆盖一个excel文件,但我真的不知道怎么做。我试过node-xlsx,exceljs但是没有一个对我有用。我不想创建一个新文件但修改现有文件。是否有人知道如何做到这一点?提前致谢。 这是我的代码:

var Excel = require("exceljs");
excel:function(req,res){
var workbook = new Excel.Workbook();
workbook.xlsx.writeFile("test.xls")
.then(function() {
var sheet = workbook.addWorksheet("My Sheet");
var worksheet = workbook.getWorksheet("My Sheet");
worksheet.columns = [
        { header: "Id", key: "id", width: 10 },
        { header: "Name", key: "name", width: 32 },
        { header: "D.O.B.", key: "DOB", width: 10 }
    ];

worksheet.addRow({id: 1, name: "John Doe", dob: new Date(1970,1,1)});
worksheet.addRow({id: 2, name: "Jane Doe", dob: new Date(1965,1,7)});
});

} 

这创建了一个名为" test.xls"的文件。但是这个文件是空的,并不包含我传入的任何信息,如行的参数。

1 个答案:

答案 0 :(得分:2)

xlsx.writeFile仅适用于写入CSV文件时。您需要打开一个流来编辑XLS文件。有关详细信息,请参阅documentation

以下是编写现有excel文件时需要执行的操作示例(未经测试)。

var Excel = require("exceljs");

excel:function(req,res){
  // This creates a file and is not needed.
  // You will need to open a stream instead
  // var workbook = new Excel.Workbook();
  // workbook.xlsx.writeFile("test.xls");

  // You can find an example of the code here:
  // https://github.com/guyonroche/exceljs#writing-xlsx
  var options = {
    filename: "./test.xls", // existing filepath
    useStyles: true, // Default
    useSharedStrings: true // Default
  };

  var workbook = new Excel.stream.xlsx.WorkbookWriter(options);
  var sheet = workbook.addWorksheet("My Sheet");
  var worksheet = workbook.getWorksheet("My Sheet");

  worksheet.columns = [
      { header:"Id", key:"id", width:10 },
      { header:"Name", key:"name", width:32 },
      { header:"D.O.B.", key:"DOB", width:10 }
  ];

  worksheet.addRow({id: 1, name: "John Doe", dob: new Date(1970,1,1)});
  worksheet.addRow({id: 2, name: "Jane Doe", dob: new Date(1965,1,7)});
  worksheet.commit(); // Need to commit the changes to the worksheet

  workbook.commit(); // Finish the workbook
};