Install the “xlsx” npm package.
$ npm install xlsx
The library can be imported directly from TS code with:
import * as XLSX from \'xlsx\';
This demo uses an array of arrays (type Array<Array<any>>
) as the core state. The component template includes a file input element, a table that updates with the data, and a button to export the data.
Then use this code sample on the input file and set the onChange function. it will give the excel data as a JSON format.
/* <input type=\"file\" (change)=\"onFileChange($event)\" multiple=\"false\" /> */ /* ... (within the component class definition) ... */ onFileChange(evt: any) { /* wire up file reader */ const target: DataTransfer = <DataTransfer>(evt.target); if (target.files.length !== 1) throw new Error(\'Cannot use multiple files\'); const reader: FileReader = new FileReader(); reader.onload = (e: any) => { /* read workbook */ const bstr: string = e.target.result; const wb: XLSX.WorkBook = XLSX.read(bstr, {type: \'binary\'}); /* grab first sheet */ const wsname: string = wb.SheetNames[0]; const ws: XLSX.WorkSheet = wb.Sheets[wsname]; /* save data */ this.data = <AOA>(XLSX.utils.sheet_to_json(ws, {header: 1})); }; reader.readAsBinaryString(target.files[0]); }