Don't skip empty rows/columns at the beginning with SheetJS

437 views Asked by At

I'm using SheetJS 2.0.0 to read .xls/.xlsx files in Javascript and automatically parse them to a 2D array:

function ReadFile(myFile) {
    var reader = new FileReader();
    reader.readAsBinaryString(myFile);
    reader.onload = function(e) {
        var data = e.target.result;
        var workbook = XLSX.read(data, {
            type: 'binary'
        });
        WorkWithData(workbook);
    };
}

function WorkWithData(workbook) {
    let sheet1Name = workbook.SheetNames[0];
    let sheet1 = workbook.Sheets[sheet1Name];
    let arr = XLSX.utils.sheet_to_json(sheet1, {header:1, defval: ""});
}

Empty rows or columns at the beginning are skipped, which means that arr[0][0] could actually be the cell C4 (not A1).

How do I keep it from skipping these empty rows/columns and instead make it give me e.g. an empty first row as ["","","",""]?

1

There are 1 answers

0
Neph On

It's possible to do this by setting the range:

function WorkWithData(workbook) {
    let sheet1Name = workbook.SheetNames[0];
    let sheet1 = workbook.Sheets[sheet1Name];
    var range = XLSX.utils.decode_range(sheet1['!ref']);
    //console.log(JSON.stringify(range));
    range.s.c = 0; //start column
    range.s.r = 0; //start row
    sheet1['!ref'] = XLSX.utils.encode_range(range);
    let arr = XLSX.utils.sheet_to_json(sheet1, {header:1, defval: ""});
}

This starts parsing the worksheet from the beginning (A1 = row 0 & column 0 in SheetJS), without skipping any empty rows or columns, up to the cell SheetJS found to be the last cell with content.

Empty rows and columns in the middle of the file are also included (see docs for header:1 here).

It's also possible to set the end with range.e.c & range.e.r. The official docs for range can be found here.