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.
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
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);
}
},
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With