SheetJS js-xlsx简介

谢阳曜
2023-12-01

https://github.com/SheetJS/js-xlsx

https://sheetjs.com/

各种电子表格格式的解析器和编写器。来自官方规范,相关文档和测试文件的Pure-JS cleanroom实现。强调解析和编写健壮性,跨格式功能与统一的JS表示兼容,以及ES3 / ES5浏览器与IE6的兼容性。

1、安装

$ npm install xlsx

2、导入库

该库可以直接从TS代码导入:

import * as XLSX from 'xlsx';

3、阵列数组

<table class="sjs-table">
  <tr *ngFor="let row of data">
    <td *ngFor="let val of row">
      {{val}}
    </td>
  </tr>
</table>

4、导出

aoa_to_sheet效用函数会返回一个工作表。导出很简单:

/* generate worksheet */
const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(this.data);

/* generate workbook and add the worksheet */
const wb: XLSX.WorkBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

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

5、导入

sheet_to_json使用该选项header:1使导入简单:

/* <input type="file" (change)="onFileChange($event)" multiple="false" /> */
/* ... (within the component class definition) ... */
  onFileChange(evt: any) {
    /* wire up file reader */
    const target: DataTransfer = <DataTransfer>(evt.target);
    if (target.files.length !== 1) throw new Error('Cannot use multiple files');
    const reader: FileReader = new FileReader();
    reader.onload = (e: any) => {
      /* read workbook */
      const bstr: string = e.target.result;
      const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});

      /* grab first sheet */
      const wsname: string = wb.SheetNames[0];
      const ws: XLSX.WorkSheet = wb.Sheets[wsname];

      /* save data */
      this.data = <AOA>(XLSX.utils.sheet_to_json(ws, {header: 1}));
    };
    reader.readAsBinaryString(target.files[0]);
  }

 

 

 

 类似资料: