6

I copied the code from this "tutorial":

https://sheetjs.com/demos/table.html

function doit(type, fn, dl) {
   var elt = document.getElementById('data-table');
   var wb = XLSX.utils.table_to_book(elt, {sheet:"Sheet JS"});
   return dl ?
    XLSX.write(wb, {bookType:type, bookSST:true, type: 'base64'}) :
    XLSX.writeFile(wb, fn || ('test.' + (type || 'xlsx')));
}

So I ended up creating this method in Angular:

exportTableToExcel() {
   var type = "xlsx"
   var elt = document.getElementsByClassName('table');
   var wb = XLSX.utils.table_to_book(elt, /*{sheet:"Sheet JS"}*/);
   return XLSX.writeFile(wb, undefined || ('test.' + (type || 'xlsx')));
}

Well, on the line of the table_to_book method, I receive this exception:

table.getElementsByTagName is not a function

I also tried this tutorial, which is similar, but it's for Angular 4, not 5.

http://vinhboy.com/blog/2017/06/13/how-to-use-sheetjs-xlsx-with-angular-4-typescript-in-the-browser/

alansiqueira27
  • 8,129
  • 15
  • 67
  • 111

2 Answers2

9

Mixing Jquery with Angular is not Recommened you can use ViewChild in Angular to Access DOM Element
you can access native DOM elements that have a template reference variable.
Example
HTML

    <div class="container">
        <table class="table" #table>
//....................

Component

import {Component,ViewChild, ElementRef} from '@angular/core';
     import * as XLSX from 'xlsx';
    export class AppComponent  {
  @ViewChild('table') table: ElementRef;

ExportToExcel()
    {
      const ws: XLSX.WorkSheet=XLSX.utils.table_to_sheet(this.table.nativeElement);
      const wb: XLSX.WorkBook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      /* save to file */
      XLSX.writeFile(wb, 'SheetJS.xlsx');

    }
    }

DEMO

Vikas
  • 11,859
  • 7
  • 45
  • 69
  • is there any way that we can add styles to cell from your code? – Abhi Nov 17 '18 at 07:17
  • @Abhi I ain't aware of it mate I posted [this](https://stackoverflow.com/questions/50087762/export-html-table-to-excel-with-css-in-angular) question on the same but did not get any answer – Vikas Nov 17 '18 at 09:24
  • How to do the same for multiple table in single sheet ? – Aniket Patil Jun 02 '21 at 06:11
  • @Vikas, how to include images in excel - https://stackblitz.com/edit/angular-nw6hhy?file=app%2Fapp.component.html – Kumaresan Sd Apr 05 '22 at 05:02
1

document.getElementsByClassName('table'); returns a NodeList, whereas getElementById('data-table'); returns a single node.

If you just want the first element with the table class, do:

var elt = document.getElementsByClassName('table')[0];
user184994
  • 17,791
  • 1
  • 46
  • 52