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/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With