user1
user1

Reputation: 586

Read a file with XLSX.readFile in the browser

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 [email protected]

Upvotes: 3

Views: 20636

Answers (2)

Ericgit
Ericgit

Reputation: 7043

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

Upvotes: 6

mayakwd
mayakwd

Reputation: 538

  • 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"

Upvotes: 3

Related Questions