0.前言

上一篇文章中,简单介绍了一种angular纯前端导出excel的方法。

这篇文章,找到第二种纯前端导出excel的方法,导出json文件。

1.方法

首先需要按照两个插件

npm install xlsx --save
npm install file-saver --save   

或者使用yarn 安装

yarn add xlsx
yarn add file-saver

在ts文件中加入

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

然后参考如下代码:

exportExcel() {
     let jsonData1=[
      {"name":"张三","sex":"男","age":"12"},
      {"name":"张三2","sex":"男","age":"11"},
      {"name":"张三3","sex":"女","age":"14"},
     ]
     let jsonData2=[
      {"name":"李四","sex":"男","age":"11"},
      {"name":"李四2","sex":"男","age":"13"},
      {"name":"李四3","sex":"女","age":"14"},
     ]
    const worksheet1: XLSX.WorkSheet = XLSX.utils.json_to_sheet(jsonData1);
    const worksheet2:XLSX.WorkSheet = XLSX.utils.json_to_sheet(jsonData2) 
     const workbook: XLSX.WorkBook = { 
      Sheets: { '表1': worksheet1,"表2":worksheet2},
      SheetNames: ['表1','表2']
    };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xls', type: 'array' });
    this.saveAsExcelFile(excelBuffer, "excel表格");
  }
  private saveAsExcelFile(buffer: any, fileName: string) {
    const data: Blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
    });
    saveAs(data, fileName  + '.xls');
  }

这个导出方法的好处是可以导出json数据,不用考虑前端表格的一些checkbox的东西还有一些额外的按钮。

分类: 前端