简体   繁体   中英

how to read portion of large excel file to prevent browser crashing using filereader and xlsx

I am able to read/parse excel files on the front end using the below code with FileReader and xlsx package. However, for very large files, this will crash the browser. I only need to read the first few rows, how can i achieve this?

working code

const xlsxParse = (file) => {
    var reader = new FileReader();
    reader.onload = function (e) {
        var data = e.target.result;
        let readedData = XLSX.read(data, { type: 'binary' });
        const wsname = readedData.SheetNames[0];
        const ws = readedData.Sheets[wsname];

        /* Convert array to json*/
        const dataParse = XLSX.utils.sheet_to_json(ws, { header: 1 });
    };
    reader.readAsBinaryString(file)
}

my attempt to read first few rows. not working

const xlsxParse = (file) => {
    var reader = new FileReader();
    reader.onprogress = (e) => {
        var data = e.target.result;
        let readedData = XLSX.read(data, { type: 'binary' });
        if (readedData) {
            const wsname = readedData.SheetNames[0];
            const ws = readedData.Sheets[wsname];

            /* Convert array to json*/
            const dataParse = XLSX.utils.sheet_to_json(ws, { header: 1 });
            console.log('dataParse', dataParse)
            if (dataParse.length > 3) {
                reader.abort()
            }
        }
    reader.readAsBinaryString(file)
}



thanks

This can help you out. Basically, sheetRows is standing for reading the first n lines:

handleFile = (file /*:File*/) => {
    /* Boilerplate to set up FileReader */
    const reader = new FileReader();
    const rABS = !!reader.readAsBinaryString;
    reader.onload = e => {
      /* Parse data */
      const bstr = e.target.result;
      const wb = XLSX.read(bstr, { type: "binary", sheetRows: 100});
      /* Get first worksheet */
      const wsname = wb.SheetNames[0];
      const ws = wb.Sheets[wsname];
      /* Convert array of arrays */
      const data = XLSX.utils.sheet_to_json(ws);
      const tableColumns = Object.keys(data[0]);
      console.log('data', data);
    };
    if (rABS) reader.readAsBinaryString(file);
    else reader.readAsArrayBuffer(file);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM