上传和下载Excel

第一步:安装包

npm install xlsx,file-saber --save

第二步:引入

import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';

第三步:上传并处理数据

reader = new FileReader(); // 定义reader


// constructor里
this.reader.onloadstart = () => {
      // this.data = [];
      // this.loading = true;
    };
    this.reader.onload = (e: any) => {
      this.appComponent.appLoading();
      // this.canSubmit = true;
      const bstr: string = e.target.result;
      const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
      const worksheet = wb.Sheets[wb.SheetNames[0]];
      const a1 = worksheet['A1']; // 获取A1的值
      const headers = {};
      const data = [];
      const keys = Object.keys(worksheet);
      keys
          // 过滤以 ! 开头的 key
          .filter(k => k[0] !== '!')
          // 遍历所有单元格
          .forEach(k => {
              // 如 A11 中的 A
              const col = k.substring(0, 1);
              // 如 A11 中的 11
              const row = parseInt(k.substring(1), 10);
              // 当前单元格的值
              const value = worksheet[k].w;
              // 保存字段名
              if (row === 1) {
                if (a1.t === 's') { // 有表头
                  headers[col] = this.jsonTitle[value];
                  return;
                } else { // 无表头
                  if (!headers['A']) {
                    headers['A'] = 'cinema_code';
                  }
                }
              }
              // 解析成 JSON
              if (!data[row]) {
                  data[row] = {};
              }
              data[row][headers[col]] = value;
          });
      // const json = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
    };
    this.reader.onloadend = () => {
    };
  // 上传
  beforeUpload = (file: any) => {
    this.reader.readAsBinaryString(file);
    return false;
  }

   

第四步:下载xlsx

  downloadExl() {
    const downJson = [];
    for (const c of this.Data) {
      const row = {
        '影**': c.ci**,
        '影**': c.ci**,
        '所**': c.ch**,
        '递**': c.po**,
        '收**': c.re**,
        '收**': c.re**,
        '说**': c.re**
      };
      downJson.push(row);
    }
    const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(downJson);

    /* 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 */
    const wbout: string = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'});

    function s2ab(s: any) {
      const buf = new ArrayBuffer(s.length);
      const view = new Uint8Array(buf);
      for (let i = 0; i !== s.length; ++i) {view[i] = s.charCodeAt(i) & 0xFF;}
      return buf;
    }

    saveAs(new Blob([s2ab(wbout)], {type: 'application/octet-stream'}), '申请硬盘列表.xlsx');
  }

说明:开发环境是angular6,使用了ng-zorro-antd中UploadFile插件

你可能感兴趣的:(angular2)