vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue 导出excel多级表头

vue前端导出多级表头的excel表的示例代码

作者:尔嵘

本文主要介绍了vue前端导出多级表头的excel表的示例代码,可以使用xlsx库来创建Excel文件,下面就来具体介绍一下,感兴趣的可以了解一下

1.安装npm依赖

npm install xlsx file-saver -S

npm install xlsx

2.引入完整的Export2Excel.js

/* eslint-disable */
import { saveAs } from 'file-saver'
import XLSX from 'xlsx'

function generateArray(table) {
    var out = [];
    var rows = table.querySelectorAll('tr');
    var ranges = [];
    for (var R = 0; R < rows.length; ++R) {
        var outRow = [];
        var row = rows[R];
        var columns = row.querySelectorAll('td');
        for (var C = 0; C < columns.length; ++C) {
            var cell = columns[C];
            var colspan = cell.getAttribute('colspan');
            var rowspan = cell.getAttribute('rowspan');
            var cellValue = cell.innerText;
            if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;

            //Skip ranges
            ranges.forEach(function (range) {
                if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
                for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
                }
            });

            //Handle Row Span
            if (rowspan || colspan) {
                rowspan = rowspan || 1;
                colspan = colspan || 1;
                ranges.push({
                s: {
                    r: R,
                    c: outRow.length
                },
                e: {
                    r: R + rowspan - 1,
                    c: outRow.length + colspan - 1
                }
                });
            };

            //Handle Value
            outRow.push(cellValue !== "" ? cellValue : null);

            //Handle Colspan
            if (colspan)
                for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
        }
        out.push(outRow);
    }
    return [out, ranges];
};

function datenum(v, date1904) {
    if (date1904) v += 1462;
    var epoch = Date.parse(v);
    return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data, opts) {
    var ws = {};
    var range = {
        s: {
            c: 10000000,
            r: 10000000
        },
        e: {
            c: 0,
            r: 0
        }
    };
    for (var R = 0; R != data.length; ++R) {
        for (var C = 0; C != data[R].length; ++C) {
            if (range.s.r > R) range.s.r = R;
            if (range.s.c > C) range.s.c = C;
            if (range.e.r < R) range.e.r = R;
            if (range.e.c < C) range.e.c = C;
            var cell = {
                v: data[R][C]
            };
            if (cell.v == null) continue;
            var cell_ref = XLSX.utils.encode_cell({
                c: C,
                r: R
            });

            if (typeof cell.v === 'number') cell.t = 'n';
            else if (typeof cell.v === 'boolean') cell.t = 'b';
            else if (cell.v instanceof Date) {
                cell.t = 'n';
                cell.z = XLSX.SSF._table[14];
                cell.v = datenum(cell.v);
            } 
            else cell.t = 's';
            ws[cell_ref] = cell;
        }
    }
    if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    return ws;
}

function Workbook() {
    if (!(this instanceof Workbook)) return new Workbook();
    this.SheetNames = [];
    this.Sheets = {};
}

function s2ab(s) {
    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;
}

export function export_table_to_excel(id) {
    var theTable = document.getElementById(id);
    var oo = generateArray(theTable);
    var ranges = oo[1];

    /* original data */
    var data = oo[0];
    var ws_name = "SheetJS";

    var wb = new Workbook(),
        ws = sheet_from_array_of_arrays(data);

    /* add ranges to worksheet */
    // ws['!cols'] = ['apple', 'banan'];
    ws['!merges'] = ranges;

    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: false,
        type: 'binary'
    });

    saveAs(new Blob([s2ab(wbout)], {
        type: "application/octet-stream"
    }), "test.xlsx")
}
// 对此方法进行修改,如下:
export function export_json_to_excel({
    multiHeader2 = [],	// 第一行表头
    multiHeader = [], // 第二行表头
    header,	// 第三行表头
    data,
    filename, //文件名
    merges = [], // 合并
    autoWidth = true,
    bookType = 'xlsx'
} = {}) {
    /* original data */
    filename = filename || '列表';
    data = [...data]
    data.unshift(header);

    for (let i = multiHeader2.length - 1; i > -1; i--) {
        data.unshift(multiHeader2[i])
    }

    for (let i = multiHeader.length - 1; i > -1; i--) {
        data.unshift(multiHeader[i])
    }

    var ws_name = "SheetJS";
    var wb = new Workbook(),
        ws = sheet_from_array_of_arrays(data);

    if (merges.length > 0) {
        if (!ws['!merges']) ws['!merges'] = [];
            merges.forEach(item => {
            ws['!merges'].push(XLSX.utils.decode_range(item))
        })
    }

    if (autoWidth) {
        /*设置worksheet每列的最大宽度*/
        const colWidth = data.map(row => row.map(val => {
        /*先判断是否为null/undefined*/
            if (val == null) {
                return {
                    'wch': 10
                };
            }
            /*再判断是否为中文*/
            else if (val.toString().charCodeAt(0) > 255) {
                return {
                    'wch': val.toString().length * 2
                };
            } else {
                return {
                    'wch': val.toString().length
                };
            }
        }))
        /*以第一行为初始值*/
        let result = colWidth[0];
        for (let i = 1; i < colWidth.length; i++) {
            for (let j = 0; j < colWidth[i].length; j++) {
                if (result[j]['wch'] < colWidth[i][j]['wch']) {
                result[j]['wch'] = colWidth[i][j]['wch'];
                }
            }
        }
        ws['!cols'] = result;
    }

    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    var wbout = XLSX.write(wb, {
        bookType: bookType,
        bookSST: false,
        type: 'binary'
    });
    saveAs(new Blob([s2ab(wbout)], {
        type: "application/octet-stream"
    }), `${filename}.${bookType}`);
}

3.vue文件中引入

import { export_json_to_excel } from "@/assets/js/Export2Excel";

4.直接上js,其他的布局之类的我就不展示了

data() {
    return {
        transforList: [], //表格数据源
        excelData: [], //表格数据,这个是你自己请求的真实数据
    }
}
methods: {
     //重置EXcel数据
    resetExcelData() {
      this.excelData = [];
      if (this.transforList.length > 0) {
        for (let excelItem of this.transforList) {
          // console.log(excelItem.transformerEntityList);
          let excelObj = {
            plantname:
              excelItem.plantname != null && excelItem.plantname != undefined
                ? excelItem.plantname
                : "",
            transName:
              excelItem.transName != null && excelItem.transName != undefined
                ? excelItem.transName
                : "",
            ea:
              excelItem.ea != null && excelItem.ea != undefined
                ? excelItem.ea
                : "",
            sa:
              excelItem.sa != null && excelItem.sa != undefined
                ? excelItem.sa
                : "", //视在功率
            pa:
              excelItem.pa != null && excelItem.pa != undefined
                ? excelItem.pa
                : "", //有功功率
            fa:
              excelItem.fa != null && excelItem.fa != undefined
                ? excelItem.fa
                : "", //无功功率
            f:
              excelItem.f != null && excelItem.f != undefined
                ? excelItem.f
                : "", //功率因数
            az:
              excelItem.az != null && excelItem.az != undefined
                ? excelItem.az
                : "", //A相绕组温度
            bz:
              excelItem.bz != null && excelItem.bz != undefined
                ? excelItem.bz
                : "", //B相绕组温度
            cz:
              excelItem.cz != null && excelItem.cz != undefined
                ? excelItem.cz
                : "", //C相绕组温度
            status:
              excelItem.status != null && excelItem.status != undefined
                ? excelItem.status
                : "",
            fuhe: "--%",
          };
          this.excelData.push(excelObj);
        }
      }
    },   

    //json格式化
    formatJson(filterVal, jsonData) {
      jsonData.map((v) => filterVal.map((j) => v[j]));
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },

    //导出方法
    exportExcel() {
      this.resetExcelData(); 
      const multiHeader = [
        [
          "站点名称",
          "变压器名称",
          "状态",
          "额定容量(kVA)",
          "视在功率(kW)",
          "负荷率(100%)",
          "有功功率(kW)",
          "无功功率(kVar)",
          "功率因数",
          "三相绕组温度",
          "",
          "",
        ]
      ]; //一级表头
      const tHeader = ["", "", "", "", "", "", "", "", "", "A", "B", "C"]; //二级表头
      const filterVal = ["plantname","transName","status","ea","sa","fuhe","pa", "fa","f","az","bz","cz"];//表头所对应后台返回的字段
      // const data = this.excelData.map(v => filterVal.map(j => v[j]));//这一行和下面得六行代码是一样得作用的
      let list = [];
      if (this.excelData == 0) {
        list = this.excelData;
      } else {
        list = this.excelData;
      }
      const data = this.formatJson(filterVal, list);//格式化
      console.log(data);
      //这个得说明一下:网上得博客每个不一样,你那我的直接用也是没啥用得,你的理解这个合并是怎么写的:根据你的多级表头,如果没有合并得从上往下写,遇到开始合并单元格的,从左往右得单行写,从上到下,直到写完整
      const merges = [
        "A1:A2",
        "B1:B2",
        "C1:C2",
        "D1:D2",
        "E1:E2",
        "F1:F2",
        "G1:G2",
        "H1:H2",
        "I1:I2",
        "J1:L1"
      ];
      export_json_to_excel({
        multiHeader, //这里是第一行的表头
        header: tHeader, //这里应该是算第二行的表头
        data,//数据
        merges,//合并行
        filename: "变压器状态" + "_" + new Date().getTime(),
        autoWidth: true,
        bookType: 'xlsx'
      });
    }
}

5.效果

总结

我的这个是两级表头,那么三级表头你应该也会做的,只是merges得细心找一下!

到此这篇关于vue前端导出多级表头的excel表的示例代码的文章就介绍到这了,更多相关vue 导出excel多级表头内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文