Search code examples
javascriptexcelxlsx

How to use XLSX library in Javascript to parse an Excel file from a particular row


I am currently using the library XLSX in Javascript to convert an Excel file into JSON object and it is giving me the results as expected.

However, the code I am currently using parses the entire Excel sheet and I don't want that. I want to start parsing the file from a particular row (row number 14).

Can this be done using the XLSX? If yes, how?

Below is my current JS code (taken from https://levelup.gitconnected.com/how-to-convert-excel-file-into-json-object-by-using-javascript-9e95532d47c5)

var selectedFile;
document.getElementById("fileUpload")
    .addEventListener("change", function (event) {
        selectedFile = event.target.files[0]
    });
document.getElementById("upload")
    .addEventListener("click", function () {
        if (selectedFile) {
            var fileReader = new FileReader();
            fileReader.onload = function (event) {
                var data = event.target.result;

                var workbook = XLSX.read(data, {
                    type: "binary"
                });
                workbook.SheetNames.forEach(sheet => {
                    let rowObject = XLSX.utils.sheet_to_row_object_array(
                        workbook.Sheets[sheet]
                    );
                    let jsonObject = JSON.stringify(rowObject, null, '\t');
                    document.getElementById("jsonData").innerHTML = jsonObject;
                });
            };
            fileReader.readAsBinaryString(selectedFile);
        }
    });

Solution

  • I am answering my own question so that it might be helpful for anyone later.

    let rowObject = XLSX.utils.sheet_to_row_object_array
    (
         workbook.Sheets[sheet], {range: 14}
    );
    
    

    The parameter range can be added in the given function which is a part of the code.

    The Excel parses from line 14 now and not the beginning of the page.