Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular集成预览表格内容js-xlsx #108

Open
deepthan opened this issue Sep 10, 2020 · 0 comments
Open

Angular集成预览表格内容js-xlsx #108

deepthan opened this issue Sep 10, 2020 · 0 comments

Comments

@deepthan
Copy link
Owner

集成预览表格内容js-xlsx

1. 首先下载依赖

yarn add xlsx

2. 再在html中写一个上传按钮和表格

html

<input type="file" (change)="onFileChange($event)" multiple="false" />

<table>
  <tr *ngFor="let row of data"  style="border:1px #ccc solid; padding:5px;">
    <td *ngFor="let val of row" style="border:1px #ccc solid; padding:5px;">
      {{val}}
    </td>
  </tr>
</table>

3. ts中引入xlsx插件并使用

ts:

import * as XLSX from 'xlsx';
...
export class xxx  {
  data: any;
  onFileChange(evt: any) {
    /* 连接文件阅读器 */
    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) => {
      const bstr: string = e.target.result;
      const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});

      /* 读取第一个表的内容 */
      const wsname: string = wb.SheetNames[0];
      const ws: XLSX.WorkSheet = wb.Sheets[wsname];

      /* 保存数据,映射到页面 */
      this.data = <any>(XLSX.utils.sheet_to_json(ws, {header: 1}));
    };
    reader.readAsBinaryString(target.files[0]);
  }
}

js-xlsx: https://github.com/SheetJS/js-xlsx/tree/master/demos/angular2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant