Reputation: 91
I need to choose an Excel file by using file input type and display that file to the specific container and I need to perform some operation. I have the same thing in javascript by using Sheet.js and xlsx... I am trying to change that to Angular, but it gives an error when sheetjsw.js ImportScript. I use canvas-datagrid, dropsheet and jquery for that purpose.
Uncaught ReferenceError: importScripts is not defined
at scripts.bundle.js:10874
I'd like help to obtain the result. For converting js things to Angular is better for me, because it reduces the time to create a new thing.
Upvotes: 2
Views: 12296
Reputation: 3079
Try this example on stackblitz
In your typescript file
import * as XLSX from 'xlsx';
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 }));
console.log(this.data);
};
reader.readAsBinaryString(target.files[0]);
}
export(): void {
/* generate worksheet */
const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(this.data);
/* generate workbook and add the worksheet */
const wb: XLSX.WorkBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
/* save to file */
XLSX.writeFile(wb, this.fileName);
}
In your Html file
<input type="file" (change)="onFileChange($event)" multiple="false" />
<table>
<tbody>
<tr *ngFor="let row of data">
<td *ngFor="let val of row">
{{val}}
</td>
</tr>
</tbody>
</table>
<button (click)="export()">Export!</button>
Upvotes: 2
Reputation: 1
You should follow these 3 steps
step 1: import ts-xlsx refer: https://www.npmjs.com/package/ts-xlsx for installation
step 2: Using FileReader convert to arraybuffer
step 3: Reading the arraybuffer with XLSX and converting as workbook
Upvotes: 0