Javascript Read Excel file on server with SheetJS

做~自己de王妃 提交于 2020-12-01 12:09:38

问题


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"


回答1:


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();



回答2:


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();
}


来源:https://stackoverflow.com/questions/48143546/javascript-read-excel-file-on-server-with-sheetjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!