Reputation: 467
I have an imported file: import ExportReportCardTemplate from "asset/files/excel/report_card_template.xls";
How can I use it with library import * as xlsx from "xlsx-js-style";
I've searching but all I get is reading xls file with input, how can I read a local file and then use it with xlsx
?
After following tpliakas' answer, I got this error:
Upvotes: 0
Views: 791
Reputation: 467
After following tpliakas answer, I had a bit adjustment and finally I can read the local file to workbook data, here is the code:
import ExportReportCardTemplate from "asset/files/excel/report_card_template.xls";
import * as xlsx from "xlsx-js-style";
const readFile = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
resolve(e.target.result);
};
reader.onerror = (e) => {
reject(e);
};
fetch(file)
.then((response) => response.blob())
.then((file) => reader.readAsBinaryString(file));
});
};
export const exportReportCardExcel = async (data) => {
try {
const binaryString = await readFile(ExportReportCardTemplate);
const workbook = xlsx.read(binaryString, { type: "binary" });
console.log("workbook:::", workbook);
} catch (error) {
console.log("error:::", error);
}
};
Upvotes: 0
Reputation: 1129
First you should read file as a binary string, so you have to do something like this
function readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
resolve(e.target.result);
};
reader.onerror = (e) => {
reject(e);
};
reader.readAsBinaryString(file);
});
}
Then you should parse this binary string to a workbook:
async function readExcel() {
// Wait for the binary string first
const binaryString = await readFile(ExportReportCardTemplate);
const wb = xlsx.read(binaryString, { type: 'binary' });
// use the wb here
}
Upvotes: 1