Reputation: 303
I'm trying to read excel values using js-xlsx
I'm able to get a cell value from a workbook sheet using the following code
if(typeof require !== 'undefined') XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xls');
var sheet_name_list = workbook.SheetNames;
var sheet = sheet_name_list.indexOf('sheet_name');
var sheetF48 = workbook.Sheets[sheet_name_list[sheet]]['F48'].v;
What I would like to do next is define a cell range so only those cell values are returned. I have figured out to get a sheet's ref by:
var sheet1 = workbook.Sheets[sheet_name_list[sheet_name]]
var range = XLSX.utils.decode_range(sheet1['!ref']);
Is it possible to define a cell range by providing the cell references?
Upvotes: 3
Views: 13942
Reputation: 188
I use the example (https://github.com/SheetJS/js-xlsx#general-structures) but i add some code to get the values.
The mnemonic here is: s for "start of range", e for "end of range", r for "row", c for "column"
var range = { s: { c: 0, r: 0 }, e: { c: 0, r: 4 } };//A1:A5
var dataRange = [];
/* Iterate through each element in the structure */
for (var R = range.s.r; R <= range.e.r; ++R) {
for (var C = range.s.c; C <= range.e.c; ++C) {
var cell_address = { c: C, r: R };
var data = XLSX.utils.encode_cell(cell_address);
dataRange.push(worksheet[data]);
}
}
Upvotes: 12
Reputation: 11
I have been working on the same problem all day. I wasn't able to find a quick solution so if you did I would like to hear. I did find a temporary fix. I had the two loops in different objects so they may be combined if wanted.
var cellStart = XLSX.utils.encode_cell({c: colStart, r: rowStart});
var cellEnd = XLSX.utils.encode_cell({c: colEnd, r: rowEnd});
var dataRange = [];
var z = Object.keys(worksheet);
var i = z.indexOf(cellStart);
while (i!=z.indexOf(cellEnd) {
dataRange.push(z[i]);
i++;
}
var desiredCells = {};
for (n of dataRange) {
/* all keys that do not begin with "!" correspond to cell addresses */
if (n[0] === '!') continue;
desiredCells[n] = worksheet[n];
}
Jade
Upvotes: 1