I have my Angular-CLI frontend development server running locally on localhost:4200
I need to get a local Excel file stored on my PC, read its content and make some calls to an API from the client side.
I'm trying to use js-xlsx, got it installed with npm install xlsx
but I can't find how to get the file and read its content.
How can I import a local excel file with js-xlsx in Angular 13?
The Excel file (XLS and XLSX) will be selected in HTML FileUpload element and will be read using HTML5 FileReader API. The read data will be parsed into a JSON Array using the xlsx Excel plugin and later the JSON Array will be used to populate a HTML Table using ng-repeat directive in AngularJS.
// read the excel file var workbook = XLSX. readFile('test. xlsx'); For reading a cell from the specific sheet, we have to provide an excel sheet name, or we can use the index of excel sheet to get the default assigned name for that excel sheet using the workbook package.
Here is working Example
onFileChange(ev) {
let workBook = null;
let jsonData = null;
const reader = new FileReader();
const file = ev.target.files[0];
reader.onload = (event) => {
const data = reader.result;
workBook = XLSX.read(data, { type: 'binary' });
jsonData = workBook.SheetNames.reduce((initial, name) => {
const sheet = workBook.Sheets[name];
initial[name] = XLSX.utils.sheet_to_json(sheet);
return initial;
}, {});
const dataString = JSON.stringify(jsonData);
document.getElementById('output').innerHTML = dataString.slice(0, 300).concat("...");
this.setDownload(dataString);
}
reader.readAsBinaryString(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