3

I am using a library called SheetJS and I want to read an excel sheet that resides on the server without using nodejs, only pure javascript. Is this possible?

There is a message in the documentation that says "readFile is only available in server environments. Browsers have no API for reading arbitrary files given a path, so another strategy must be used"

With the above message, I assume the author is referring to a situation where the file is residing on the client side.

This is what I have done so far

var wb = XLSX.readFile("myFile.xlsx"); //my file is in same directory on server

I get error "xlsx.full.min.js:22 Uncaught TypeError: Cannot read property 'readFileSync' of undefined"

electricalbah
  • 2,227
  • 2
  • 22
  • 36

2 Answers2

7

This worked for me

   /* set up async GET request */
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.responseType = "arraybuffer";

    req.onload = function(e) {
      var data = new Uint8Array(req.response);
      var workbook = XLSX.read(data, {type:"array"});

      /* DO SOMETHING WITH workbook HERE */
    }

    req.send();
electricalbah
  • 2,227
  • 2
  • 22
  • 36
  • this didn't work for me - specially type: "array" gives me null.. if i change it to type: "buffer"- i get one sheet.. but the data is random numbers and not something my excel has - https://stackoverflow.com/questions/59214951/how-to-read-excel-from-a-url-in-react-js – Manny Dec 09 '19 at 07:45
1

I had many issues with reading the file server-side, with a number of errors including type error, charCodeAt. So this provides a client and server-side solution using a reader. The excel file comes from a file upload button, and uses node.js. Client-side:

let excelInput = document.getElementById("fileToUpload");
let excelFile = excelInput.files[0];
let reader = new FileReader();

So you get the file using files[0] from that element and create a fileReader.

You can see Aymkdn's solution on Github. https://github.com/SheetJS/sheetjs/issues/532. It uses the Uint8Array to work.

reader.readAsArrayBuffer(excelFile);
reader.onload = function() {
  excelArray = new Uint8Array(reader.result); //returns Uint8Array using the result of reader

  let binary = "";
  var length = excelArray.byteLength;
  for (var i = 0; i < length; i++) {
    binary += String.fromCharCode(excelArray[i]); 
    //uses a for loop to alter excelArray to binary
  }

  let formData = new FormData(); //create form data
  formData.append("excel", binary); //append binary to it

  fetch('/excel', {method: "POST", body: formData}) //post as normal
  .then((data) => {
    console.log('Success:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });
}

Server-side:

app.post('/excel', function(req, res) {
    let data = req.body;
    var workbook = sheetJS.read(data, {type: 'buffer'});
    console.log("workbook is", workbook);
    res.send();
}
imatwork
  • 523
  • 6
  • 16