node.js – 用nodeJs覆盖excel文件

我想用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”的文件,但此文件为空,并且不包含我传入的任何信息,如行的参数.

最佳答案 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
};
点赞