vue JSON数据导出为 多个sheet表的excel文件

2018/06/26 17:20
阅读数 2.4K
<!DOCTYPE html>
<html lang="en">
  <head></head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <script src="https://cdn.bootcss.com/xlsx/0.15.1/xlsx.full.min.js"></script>
  </head>
  <body>
    <script>
      // 数据
      let data = { '基本信息': [{name: '李四', sex: 'nan', age: 12}], '成绩': [{class: '计算机', teacher: 'Mrs wang', score: 90}] };
      let columnHeaders = { '基本信息': ['name', 'sex', 'age'], '成绩': ['class', 'teacher', 'score']}
      outputXlsxFile(
        data,
        [{ wch: 50 }, { wch: 50 }, { wch: 10 }],
        "test-xlsx"
      );

      function outputXlsxFile(data, wscols, xlsxName) {
        let sheetNames = [];
        let sheetsList = {};
        const wb = XLSX.utils.book_new();

        for (let key in data) {
          sheetNames.push(key);
          let columnHeader = columnHeaders[key] // 此处是每个sheet的表头
          let temp = transferData(data[key], columnHeader);
          sheetsList[key] = XLSX.utils.aoa_to_sheet(temp);
          sheetsList[key]["!cols"] = wscols;
        }

        wb["SheetNames"] = sheetNames;
        wb["Sheets"] = sheetsList;

        XLSX.writeFile(wb, xlsxName + ".xlsx");
      }

      function transferData(data, columnHeader) {
        let content = [];
        content.push(columnHeader);
        data.forEach((item, index) => {
          let arr = [];
          columnHeader.map(column =>{
            arr.push(item[column]);
          })
          content.push(arr);
        });
        return content;
      }
    </script>
  </body>
</html>

 
注意 上面的引入必须是xlsx.full.min.js
<script src="https://cdn.bootcss.com/xlsx/0.15.1/xlsx.full.min.js"></script>
 
展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部