Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Read Excel file and save every worksheet as CSV file.
var filename = `${__dirname}/../server/data/sample.xlsx`;
// Read from a file give path to Excel/xlsx file.
var workbook = new Excel.Workbook();
workbook.xlsx
.readFile(filename)
.then(function() {
console.log('Loaded!');
// Write to a file.
// use workbook
var worksheets = workbook.worksheets;
// var worksheets = workbook.getWorksheet(1);
for (var i = 0; i < worksheets.length; ++i) {
var worksheet = worksheets[i];
console.log(worksheet.name);
var workbookCSV = new Excel.Workbook();
workbookCSV._worksheets = [worksheet];
workbookCSV.csv
.writeFile(filename + "." + i + worksheet.name + ".csv")
.then(function() {
console.log('CSV Saved!');
// done
});
}
// Iterate over all sheets
// Note: workbook.worksheets.forEach will still work but this is better
workbook.eachSheet(function(worksheet, sheetId) {
console.log(worksheet.name);
console.log(sheetId);
console.log(
"============================================================="
);
// // Iterate over all rows that have values in a worksheet
// worksheet.eachRow(function(row, rowNumber) {
// console.log(
// "Row " + rowNumber + " = " + JSON.stringify(row.values)
// );
// // Iterate over all cells in a row (including empty cells)
// console.log("-------------------------------");
// row.eachCell({ includeEmpty: true }, function(cell, colNumber) {
// // console.log(cell);
// // console.log("Cell " + colNumber + " = " + cell.value);
// // var col = worksheet.getColumn(colNumber);
// var resultValue = cell.value;
// if (isObject(cell.value)) {
// resultValue = cell.value.result;
// }
// console.log("Cell Value" + colNumber + " = " + resultValue);
// });
// });
// // // Iterate over all rows (including empty rows) in a worksheet
// // worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) {
// // console.log(
// // "Row " + rowNumber + " = " + JSON.stringify(row.values)
// // );
// // });
});
})
.catch(function(e) {
console.log(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.