Search code examples
reactjslocal-filesxlsx-js

ReactJS xlsx-js-style read local xls file


I have an imported file: import ExportReportCardTemplate from "asset/files/excel/report_card_template.xls";

How can I use it with library import * as xlsx from "xlsx-js-style";

I've searching but all I get is reading xls file with input, how can I read a local file and then use it with xlsx?

After following tpliakas' answer, I got this error: enter image description here


Solution

  • After following tpliakas answer, I had a bit adjustment and finally I can read the local file to workbook data, here is the code:

    import ExportReportCardTemplate from "asset/files/excel/report_card_template.xls";
    import * as xlsx from "xlsx-js-style";
    
    const readFile = (file) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          resolve(e.target.result);
        };
        reader.onerror = (e) => {
          reject(e);
        };
        fetch(file)
          .then((response) => response.blob())
          .then((file) => reader.readAsBinaryString(file));
      });
    };
    
    export const exportReportCardExcel = async (data) => {
      try {
        const binaryString = await readFile(ExportReportCardTemplate);
        const workbook = xlsx.read(binaryString, { type: "binary" });
        console.log("workbook:::", workbook);
      } catch (error) {
        console.log("error:::", error);
      }
    };