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';
|
|
|
|
|
2018-01-09 07:36:02 +00:00
|
|
|
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">
|
2017-09-12 20:02:06 +00:00
|
|
|
{{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] ];
|
2017-12-30 05:40:35 +00:00
|
|
|
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
|
|
|
|
2017-08-05 22:44:17 +00:00
|
|
|
onFileChange(evt: any) {
|
2017-06-21 23:10:36 +00:00
|
|
|
/* wire up file reader */
|
2017-08-05 22:44:17 +00:00
|
|
|
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();
|
2017-08-05 22:44:17 +00:00
|
|
|
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
|
|
|
|
2017-08-05 22:44:17 +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]);
|
|
|
|
}
|
|
|
|
|
2017-08-05 22:44:17 +00:00
|
|
|
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 */
|
2018-02-03 20:46:32 +00:00
|
|
|
XLSX.writeFile(wb, this.fileName);
|
2017-06-21 23:10:36 +00:00
|
|
|
}
|
|
|
|
}
|