2

I am trying to read the .xlsx file using FileReader and XLSX module. So If I am trying to read the whole .xlsx file then it's working fine. But I just want to read only the top 5 to 10 lines of .xlsx file. so that's why instead of passing an original file which can be quite large some time greater than 100mb. I am just passing a slice of the file to the FileReader so it can read the file faster otherwise if I pass the original file which can be 100mb then it will take too much time in processing and I do not want to process a whole file to just read top 10 lines.
Here is the code :

onFile(event:any){
let data = event.target.files[0];
let fileReader = new FileReader();
fileReader.onload = (e) => {
  let arrayBuffer = e.target.result;
  console.log(arrayBuffer);
  let workbook = XLSX.read(arrayBuffer, {type:"array"});
  let first_sheet_name = workbook.SheetNames[0];
  let worksheet = workbook.Sheets[first_sheet_name];
  console.log(XLSX.utils.sheet_to_json(worksheet,{raw:true}));
}
fileReader.readAsArrayBuffer(data.slice(0,500));
}

so I think the problem here is during slicing I am trying to slice starting 500 bytes using the slice method and then passing it to the FileReader. so my question is here how can I slice a .xlsx file properly because using the current way file getting corrupt.

Note: other files like .csv or .tsv working fine even if I am slicing them using the current way. I was also able to read the .xlsx file using the same way a few months ago. but I don't know why I am facing this issue now.

Aakash Giri
  • 53
  • 1
  • 8
  • 1
    .csv or .tsv are plain text files. XLSX files are ZIP archives with a bunch of XML files and whatever inside. You can't "slice" Excel files just because there is no order what comes first in the ZIP file. If you want to speed-up loading modify the loading code to only process the part you want to load. – Robert Jan 14 '22 at 13:01
  • @Robert thankyou for clarification can you provide me an example code to speed up the loading? I mean how can I read only top 10 lines of the xlsx file. Because I want to read only a small part of xlsx as arraybuffer. If i am going to pass a whole xlsx file in readAsArrayBufffer method then it can crash the browser or maybe will take too much time in loading. – Aakash Giri Jan 14 '22 at 13:59
  • Sorry I am not familiar with sheetjs. Open the XLSX file in an ZIP viewer and see it's internal structure and complexity so you understand why you can't just pick the data that comes first and think it can be interpreted as Excel sheet. – Robert Jan 14 '22 at 14:36

0 Answers0