Q: Is it possible to read xlsx in react if office is not installed on windows machine? Currently I am using below code to read xlsx file in react when my system having office (excel) installed. But the same is throwing error on other machine where office(excel) is not installed.
Error is at this point console.log(this.state.file.type)
Here is console.log :
lastModified: 1595606065652
lastModifiedDate: Fri Jul 24 2020 15:54:25 GMT+0000 (Greenwich Mean Time) {}
name: "ExamAnswer.xlsx"
size: 14266
type: "" // here type is null
webkitRelativePath: ""
__proto__: File

So, could you please tell how to read file type
handleExamInputFile() {
const reader = new FileReader();
const rABS = !!reader.readAsBinaryString;
console.log("file", this.state.file);

console.log(this.state.file.type);
let fileType =
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if (this.state.file.size > 0) {
  console.log(this.state.file.size);

  if (this.state.file.type === fileType) {
    if (rABS) {
      reader.readAsBinaryString(this.state.file);
    } else {
      reader.readAsArrayBuffer(this.state.file);
    }

    reader.onload = (e) => {
      const bstr = e.target.result;
      const wb = XLSX.read(bstr, {
        type: rABS ? "binary" : "array",
        bookVBA: true,
      });

      const wsname = wb.SheetNames[0];
      const ws = wb.Sheets[wsname];
      const data = XLSX.utils.sheet_to_json(ws, {
        raw: true,
      });

      const header = [];
      const columnCount = XLSX.utils.decode_range(ws["!ref"]).e.c + 1;
      for (let i = 0; i < columnCount; ++i) {
        if (ws[`${XLSX.utils.encode_col(i)}1`] != undefined) {
          header[i] = ws[`${XLSX.utils.encode_col(i)}1`].v;
        }
      }
      console.log(header);
      let headerMustHave = ["Exam Name", "EId", "Name"];
      // let ifFound = header.every(function (val) {
      //   console.log(val);
      //   return headerMustHave.indexOf(val) !== -1;
      // });
      let checker = (arr, target) => target.every((v) => arr.includes(v));
      let ifFound = checker(header, headerMustHave);
      console.log(ifFound);
      if (ifFound === true) {
        for (var i = 0; i < data.length; i++) {
          let excel_date = this.ExcelDateToJSDate(data[i]["Report Date"]);

          data[i]["Report Date"] = excel_date;
        }

        this.setState({
          data: data,
          result: JSON.stringify(data),
          cols: make_cols(ws["!ref"]),
        });

        const exceldata = JSON.parse(this.state.result);

        const excelList = exceldata.map((data) => data);

        const excel = { data: excelList };
        const url = "http://localhost:8000/upload";
        const config = {
          headers: {
            Accept: "*",
            "Content-Type": "application/json",
            "Allow-Control-Allow-Origin": "*",
            // Accept: "application/json",
          },
        };
        return post(url, excel, config).then((response) => {
          toast.success(response.data, {
            position: toast.POSITION.TOP_CENTER,
          });
          document.getElementById("file1").value = "";
          this.setState({ file: "" });
        });
      } else {
        toast.error("Some columns are not presented in uploaded file.", {
          position: toast.POSITION.TOP_CENTER,
          autoClose: 3000,
        });
        this.setState({ file: "" });
      }
    };
  } else {
    toast.error(
      "This file format is not supported. Please select an .xlsx file.",
      {
        position: toast.POSITION.TOP_CENTER,
        autoClose: 3000,
      }
    );
    this.setState({ file: "" });
  }
} else {
  toast.error("Please select .xlsx file to upload.", {
    position: toast.POSITION.TOP_CENTER,
    autoClose: 3000,
  });
  this.setState({ file: "" });
 }
}

Alternatively, is it possible to read the same xlsx file through python on above type machine?
TIA

A: Since this is React.js code, it's running client-side, in a browser.
Your problem with type being empty is that not all machines and browsers know how to map the file type .xlsx to the MIME type 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; those with Excel, or maybe LibreOffice installed, certainly might, but even that's not a given. Whether or not Excel is actually installed has no bearing on whether the XLSX.js library you're using can actually parse the file (since the browser doesn't know about Excel).
As I mentioned in the comments, you can simply optionally look at the extension of the file uploaded – and even that's not necessary; you could just attempt to pass the file to XLSX; it would fail to parse files that are not XLSX documents anyway.
Here's a refactoring of your code to move to promise-based asynchronicity, moving the actual processing code out of the React component, so it's more easily testable.
In addition, you seemed to be doing some strange to-JSON-from-JSON coercion before posting the data; I got rid of that (and all of the Toast error handling for a more minimal example)...
function ExcelDateToJSDate(x) {
  return x; // TODO: implement
}

function processWorkbook(wb) {
  const wsname = wb.SheetNames[0];
  const ws = wb.Sheets[wsname];
  const data = XLSX.utils.sheet_to_json(ws, {
    raw: true,
  });

  const header = [];
  const columnCount = XLSX.utils.decode_range(ws["!ref"]).e.c + 1;
  for (let i = 0; i < columnCount; ++i) {
    const col = `${XLSX.utils.encode_col(i)}1`;
    if (ws[col] != undefined) {
      header[i] = ws[col].v;
    }
  }
  console.log(header);
  const headerMustHave = ["Exam Name", "EId", "Name"];
  const checker = (arr, target) => target.every((v) => arr.includes(v));
  let ifFound = checker(header, headerMustHave);
  if (ifFound === true) {
    for (var i = 0; i < data.length; i++) {
      let excel_date = ExcelDateToJSDate(data[i]["Report Date"]);
      data[i]["Report Date"] = excel_date;
    }
  }
  return { ws, data };
}

/**
 * Read a DOM File into a binary string or array buffer; returns a Promise.
 */
function readFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    let type;
    if (reader.readAsBinaryString) {
      reader.readAsBinaryString(file);
      type = "binaryString";
    } else {
      reader.readAsArrayBuffer(file);
      type = "arrayBuffer";
    }
    reader.onload = (event) => {
      resolve({ type, data: event.target.result });
    };
    reader.onerror = (event) => reject(event);
  });
}

async function processExamInputFile(file) {
  if (!file) {
    throw new Error("No file selected.");
  }
  if (
    !(
      file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
      file.name.endsWith(".xlsx")
    )
  ) {
    throw new Error("Invalid file type or extension.");
  }
  const { data, type } = await readFile(file);
  const wb = XLSX.read(data, {
    type: type === "binaryString" ? "binary" : "array",
    bookVBA: true,
  });
  return processWorkbook(wb);
}

class X {
  async handleExamInputFile() {
    try {
      const { ws, data } = await processExamInputFile(this.state.file);
      this.setState({
        data: data,
        result: JSON.stringify(data),
        cols: make_cols(ws["!ref"]),
      });
      await post(
        "http://localhost:8000/upload",
        { data },
        {
          headers: {
            Accept: "*",
            "Content-Type": "application/json",
            "Allow-Control-Allow-Origin": "*",
          },
        },
      );
    } catch (err) {
      console.log(err);  // TODO: improve
    }
  }
}

