关于javascript:前端导出excel

37次阅读

共计 1446 个字符,预计需要花费 4 分钟才能阅读完成。

<template>
  <div style="display:inline-block;vertical-align: middle;">
    <Button
      type="primary"
      size="small"
      style="float:right"
      :disabled='!options.data.length'
      @click="_export"
    > 谬误导出 </Button>
  </div>
</template>
<script>
import XLSX from "xlsx";
import "xlsx/dist/xlsx.full.min.js";
import saveAs from "file-saver/FileSaver.min.js";

export default {data() {
    return {
      modal: {isShow: false},
      limitNumber: 30000, // 单个 excel 下限数据量
      totalCount: 0,
      exportArr: [],
      changeObj: {}};
  },
  methods: {_export() {let returnArr = [];
      let columns = this.options.columns;
      let data = this.options.data;
      let tempArr = [];
      columns.forEach(item => tempArr.push(item.label));
      returnArr.push(tempArr);
      data.forEach(item => {let keyArr = [];
        columns.forEach(col => keyArr.push(item[col.prop]));
        returnArr.push(keyArr);
      });

      const wopts = {bookType: 'xlsx', bookSST: false, type: 'binary'};
      const wb = {SheetNames: ['Sheet1'], Sheets: {}, Props: {} };

      let objName = this.options.name ? this.options.name : "数据导出";

      // wb.Sheets["Sheet1"] = XLSX.utils.json_to_sheet(returnArr);
      wb.Sheets['Sheet1'] = XLSX.utils.aoa_to_sheet(returnArr);

      saveAs.saveAs(new Blob([s2ab(XLSX.write(wb, wopts))], {type: "application/octet-stream"}),
        objName + "." + (wopts.bookType == "biff2" ? "xls" : wopts.bookType)
      );

      function s2ab(s) {if (typeof ArrayBuffer !== "undefined") {var buf = new ArrayBuffer(s.length);
          var view = new Uint8Array(buf);
          for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
          return buf;
        } else {var buf = new Array(s.length);
          for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
          return buf;
        }
      }
    }
  },

  props: ["options"]
};
</script>

正文完
 0