Banani720
Banani720

Reputation: 159

Show Excel File Contents as HTML Table Angular

I am trying to import an Excel File and show it's contents as a table within the web-app

What I have so far:

read-excel.component.ts

import { Component, ElementRef, ViewChild, OnInit, Output } from '@angular/core';
import * as xlsx from 'xlsx';
const { read, utils: { sheet_to_json } } = xlsx;


@Component({
  selector: 'app-read-excel',
  templateUrl: './read-excel.component.html',
  styleUrls: ['./read-excel.component.css']
})

export class ReadExcelComponent implements OnInit {

constructor() {}

ngOnInit () {


}

$mport(data: any, options: xlsx.ParsingOptions): any[][] {
    const workBook: xlsx.WorkBook = read(data, options)
    const workSheet: xlsx.WorkSheet = workBook.Sheets[workBook.SheetNames[0]]
    return sheet_to_json(workSheet, {header : 1, raw: true})
}

}

and in my read-excel.component.html

<div>
<h2> Read Excel Files</h2>
<input  type="file" id="input" (change)="$mport()">
<div id='result-table'></div>
<pre id='result'></pre>


</div>

however, when I import the file, I am met with the error Error: Cannot read property 'slice' of undefined in the console

Upvotes: 0

Views: 5940

Answers (1)

dasunse
dasunse

Reputation: 3079

Try with this stackblitz example

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);
  }

Upvotes: 1

Related Questions