skip to Main Content

I need to store a excel spreadsheet template on a webpage and populate that spreadsheet with information from a form when a button is pressed. But I can’t figure out how to fetch the excel template I’m storing locally into somewhere where I can manipulate it using xlsx or any kind of excel manipulation tool.

fetch('../public/Template.xlsx')
      .then(res => res.json())
Uncaught (in promise) SyntaxError: Unexpected token 'P', "PK
async function getTemplate() {
    let wb;
    await fetch("../public/Template.xlsx")
    .then(res => {const file = xlsx.readFile(res)}).then((data => {
      wb = data;
    }))
    return wb
  }
Argument of type 'Response' is not assignable to parameter of type 'string'.ts(2345

I tried using fetch API in a few different ways since some people had said that you could retrieve it if the spreadsheet is in the public folder, but the result can’t be converted to JSON, it gets this error, and so I don’t know how is the "correct" way to access this data and return it.

I’m using Typescript, and a React app with Vite, I’m quite inexperienced in web development generally so I’m sorry if I’m missing the obvious here.

2

Answers


  1. When you use fetch you’re retrieving the data programmatically … but you want it returned as if a user clicked on a download link, so you need a different approach.

    Instead, use window.open and point it to the file you want to download:

    window.open(urlToDownload, '_blank');
    

    https://developer.mozilla.org/en-US/docs/Web/API/Window/open

    Login or Signup to reply.
  2. you need to use

    var workbook = XLSX.read(data, opts); 
    

    here cuz it support when data is instance of ArrayBuffer (https://www.npmjs.com/package/xlsx#acquiring-and-extracting-data)
    and using:

    fetch(url).then(r=>r.arrayBuffer())
    

    you can get array buffer
    so you can use this:

    async function loadXLSX(url) {
        return XLSX.read( await fetch(url).then(r=>r.arrayBuffer()) )
    }
    
    let wb = await loadXLSX('test file.xlsx')
    

    and about json in this lib:
    https://www.npmjs.com/package/xlsx#generating-json-and-js-data

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search