Reputation: 18401
i want to overwrite an excel file with sailsJs, but really i don't know how to do it.I tried node-xlsx,exceljs but none works for me.I don't want to create a new file but modify an existing file. is there anyone who have an idea of how to do it? Thanks in advance. this is my code:
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)});
});
}
This created a file named "test.xls" but this file is empty and doesn't contain any of the informations i pass in like parameters of the row.
Upvotes: 4
Views: 6054
Reputation: 1294
xlsx.writeFile only works for when writing to CSV files. You would need to open a stream to edit an XLS file. More information is available in the documentation.
Here is an example (not tested) of what you would need to do to write to an existing excel file.
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
};
Upvotes: 4