sheetjs/demos/angular2/src/app/sheetjs.component.ts

61 lines
1.6 KiB
TypeScript
Raw Normal View History

2017-06-21 23:10:36 +00:00
/* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
/* vim: set ts=2: */
import { Component } from '@angular/core';
import * as XLSX from 'xlsx';
type AOA = any[][];
2017-06-21 23:10:36 +00:00
@Component({
selector: 'sheetjs',
template: `
<input type="file" (change)="onFileChange($event)" multiple="false" />
<table class="sjs-table">
<tr *ngFor="let row of data">
<td *ngFor="let val of row">
{{val}}
</td>
2017-06-21 23:10:36 +00:00
</tr>
</table>
<button (click)="export()">Export!</button>
`
})
export class SheetJSComponent {
2017-09-24 23:40:09 +00:00
data: AOA = [ [1, 2], [3, 4] ];
wopts: XLSX.WritingOptions = { bookType: 'xlsx', type: 'array' };
2017-09-24 23:40:09 +00:00
fileName: string = 'SheetJS.xlsx';
2017-06-21 23:10:36 +00:00
onFileChange(evt: any) {
2017-06-21 23:10:36 +00:00
/* wire up file reader */
const target: DataTransfer = <DataTransfer>(evt.target);
2017-09-24 23:40:09 +00:00
if (target.files.length !== 1) throw new Error('Cannot use multiple files');
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
2017-06-21 23:10:36 +00:00
/* read workbook */
2017-09-24 23:40:09 +00:00
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
2017-06-21 23:10:36 +00:00
/* grab first sheet */
2017-09-24 23:40:09 +00:00
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
2017-06-21 23:10:36 +00:00
/* save data */
2017-09-24 23:40:09 +00:00
this.data = <AOA>(XLSX.utils.sheet_to_json(ws, {header: 1}));
2017-06-21 23:10:36 +00:00
};
reader.readAsBinaryString(target.files[0]);
}
export(): void {
2017-06-21 23:10:36 +00:00
/* generate worksheet */
2017-09-24 23:40:09 +00:00
const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(this.data);
2017-06-21 23:10:36 +00:00
/* generate workbook and add the worksheet */
2017-09-24 23:40:09 +00:00
const wb: XLSX.WorkBook = XLSX.utils.book_new();
2017-06-21 23:10:36 +00:00
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
/* save to file */
XLSX.writeFile(wb, this.fileName);
2017-06-21 23:10:36 +00:00
}
}