简体   繁体   中英

how to display excel file in angular4

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.

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM