Read a file with XLSX.readFile

别等时光非礼了梦想. 提交于 2021-01-29 11:48:46

问题


In Typescript, I've got the error "Cannot read property 'replace' of undefined" executing:

const xlsx = XLSX.readFile(fileName);

filename is a path to an existing file; I've read that "readFile is only available in server environments. Browsers have no API for reading arbitrary files given a path, so another strategy must be used." How can I do?

Edit: the file I'm trying to read is an xlsx; it's zipped: does the library have a bug? I'm running xlsx@0.15.1


回答1:


  • NodeJS API allows you to work with file system API.
  • Browser API allows you to fetch any kind of data from server.

So basically you need to place your file on some server (local or remote), then fetch it and read it with XLSX.read(data, options)

fetch('http://localhost:8080/public/filename.ext')
   .then(response => response.arrayBuffer())
   .then(buffer => {
         const xlsx = XLSX.read(new Uint8Array(data, {type: 'array'}));
         // process data here
         ...
    })
    .catch(err => console.error(err));

The other way, if you don't want to host your file on the server, you can try FileReader API, which is a bit more complicated.

You can read about FileReader and File in this article: "Reading files in JavaScript using the File APIs"




回答2:


reading a file in xlsx is easy and flexible, you can store data in db or in json file, so that later you can render the data

 <input
        type="file"
        onChange={e => {
          const file = e.target.files[0]
          readExcel(file)
        }}
/>

now read the file when you upload it

const readExcel = async (file: any) => {
    const fileReader = await new FileReader()
    fileReader.readAsArrayBuffer(file)

    fileReader.onload = (e: any) => {
      const bufferArray = e?.target.result
      const wb = XLSX.read(bufferArray, { type: "buffer" })
      const wsname = wb.SheetNames[0]
      const ws = wb.Sheets[wsname]

      const data = XLSX.utils.sheet_to_json(ws)
      const fileName = file.name.split(".")[0]

      console.log(data)
    }

github repo



来源:https://stackoverflow.com/questions/57871476/read-a-file-with-xlsx-readfile

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