Javascript: How to read and get data from an excel file

·

1 min read

For myself, I'm using this function

async function readDataFromExcel(file: File): Promise<any[]> {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = () => {
      const arrayBuffer = <any> fileReader.result;
      const data = new Uint8Array(arrayBuffer);
      const arr = new Array();
      for (let i = 0; i !== data.length; ++i) { arr[i] = String.fromCharCode(data[i]); }
      const bstr = arr.join('');
      const workbook = XLSX.read(bstr, { type: 'binary' });
      const firstsheetname = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstsheetname];
      const sheet = JSON.parse(JSON.stringify(XLSX.utils.sheet_to_json(worksheet, { raw: true })));

      if (!sheet || sheet.length < 1) {
        reject('File Empty!');
      }

      resolve(sheet);
    };
    fileReader.onerror = (e) => {
      reject(e);
    };

    fileReader.readAsArrayBuffer(file);
  });
}

In my case, I just have to read one sheet. If you want to read more sheets, you can use the loop for workbook.SheetNames

Hope it's helpful.