jogarcia
jogarcia

Reputation: 2742

upload and process excel file in vue

Am trying to upload an xlsx excel file and process it in my Vue app. But it's failing, throwing an error. Which makes me think that I'm not using or importing the library correctly since in a node projects works fine.

Am using the xlsx library.

Code

template

<template>
  <div id="app">
    <input type="file" @change="onChange" />
  </div>
</template>

script

import XLSX from "xlsx"

export default {
  name: "App",
  methods: {
    onChange(event) {
      this.file = event.target.files ? event.target.files[0] : null;
      let workbook = XLSX.readFile(this.file);
      console.log('workbook1');
      console.log(workbook);
      console.log('SheetNames');
      console.log(workbook.SheetNames);
    },
  }
};

At this point even being pointed to the a correct library if there is one would be very appreciated. Thanks in advance.

This is my codesandbox of the problem:

https://codesandbox.io/s/nervous-montalcini-w3qhy?file=/src/App.vue

Upvotes: 4

Views: 35970

Answers (4)

wobsoriano
wobsoriano

Reputation: 13434

You need to set up a FileReader first then read the file as a binary string so you can pass it to XLSX.

export default {
  methods: {
    onChange(event) {
      this.file = event.target.files ? event.target.files[0] : null;
      if (this.file) {
        const reader = new FileReader();

        reader.onload = (e) => {
          /* Parse data */
          const bstr = e.target.result;
          const wb = XLSX.read(bstr, { type: 'binary' });
          /* Get first worksheet */
          const wsname = wb.SheetNames[0];
          const ws = wb.Sheets[wsname];
          /* Convert array of arrays */
          const data = XLSX.utils.sheet_to_json(ws, { header: 1 });
        }

        reader.readAsBinaryString(this.file);
      }
    },
  }
};

Upvotes: 7

Shiva Pal
Shiva Pal

Reputation: 11

import it ->

import * as XLSX from "xlsx";

Upvotes: 1

Wise Invoker
Wise Invoker

Reputation: 41

I did it through read-excel-file npm package. Here is my code.

<template>
...
<input type="file" @change="onFileChange" />
...
</template>
import readXlsxFile from 'read-excel-file'
export default {
...
methods: {
  onFileChange(event) {
    let xlsxfile = event.target.files ? event.target.files[0] : null;
    readXlsxFile(xlsxfile).then((rows) => {
      console.log("rows:", rows)
    })
  }
}

Upvotes: 3

mai elrefaey
mai elrefaey

Reputation: 392

NODE ONLY! Attempts to read filename and parse ! you can use another library of vuejs

Upvotes: 0

Related Questions