Skip to content

Instantly share code, notes, and snippets.

@davidhq
Last active October 8, 2023 02:03
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davidhq/0afed70985842cac6fc4e00f88a71bd2 to your computer and use it in GitHub Desktop.
Save davidhq/0afed70985842cac6fc4e00f88a71bd2 to your computer and use it in GitHub Desktop.
Execute excel workbooks through node.js
const FormulaParser = require('hot-formula-parser').Parser;
const parser = new FormulaParser();
const Excel = require('exceljs');
const workbook = new Excel.Workbook();
function getCellResult(worksheet, cellLabel) {
if (worksheet.getCell(cellLabel).formula) {
return parser.parse(worksheet.getCell(cellLabel).formula).result;
} else {
return worksheet.getCell(cellCoord.label).value;
}
}
workbook.xlsx.readFile('./doc.xlsx').then(() => {
var worksheet = workbook.getWorksheet(1);
parser.on('callCellValue', function(cellCoord, done) {
if (worksheet.getCell(cellCoord.label).formula) {
done(parser.parse(worksheet.getCell(cellCoord.label).formula).result);
} else {
done(worksheet.getCell(cellCoord.label).value);
}
});
parser.on('callRangeValue', function(startCellCoord, endCellCoord, done) {
var fragment = [];
for (var row = startCellCoord.row.index; row <= endCellCoord.row.index; row++) {
var colFragment = [];
for (var col = startCellCoord.column.index; col <= endCellCoord.column.index; col++) {
colFragment.push(worksheet.getRow(row + 1).getCell(col + 1).value);
}
fragment.push(colFragment);
}
if (fragment) {
done(fragment);
}
});
worksheet.getCell('C12').value = 500;
console.log(getCellResult(worksheet, 'C13'));
});
@shubhammm4u
Copy link

It worked. Thanks a ton!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment