当前位置: 代码网 > it编程>编程语言>Javascript > vue前端导出多级表头的excel表的示例代码

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

2024年07月02日 Javascript 我要评论
1.安装npm依赖npm install xlsx file-saver -snpm install xlsx2.引入完整的export2excel.js/* eslint-disable */imp

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多级表头内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com