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/

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

is there any way that we can add styles to cell from your code?
@Abhi I ain't aware of it mate I posted this question on the same but did not get any answer
How to do the same for multiple table in single sheet ?
@Vikas, how to include images in excel - stackblitz.com/edit/…
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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.