参考:

https://blog.csdn.net/xingchen678/article/details/102686621:关于表头设置可参考该文章

https://blog.csdn.net/qq_33430445/article/details/106349858:实现代码可以参考此处

安装依赖

npm install --save xlsx file-saver

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}`);
}

Vue 中使用

	// 导出
    handleExportMarketingList() {
        // 懒加载,@/common/vendor/Export2Excel 此路径为本地路径
        import('@/common/vendor/Export2Excel').then((excel) => {
            const multiHeader = [
                [
                    '序号', '项目基本信息', '', '', '', '', '', '', '', '', '', '', '', '', '', '立项信息', '', '',
                    '项目周度进度汇报', '', '招标信息', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
                    '招标文件分析', '', '', '标书完成情况', '', '', '中标信息', '', '', '', '竞品价格收集', '', '', '', '', '', '复盘分析报告',
                ],
            ];
            const multiHeader2 = [
                [
                    '', '阶段', '项目负责人', '所属区域', '省份', '地级市', '客户名称', '客户性质', '现有服务商', '服务业态', '项目体量(万元/年)',
                    '本次招标期限(年)', '合同到期时间', '预计招标时间', '其他情况说明', '立项时间', '投标负责人', '立项流程', '日期', '项目周度进度汇报内容',
                    '招标公告发布时间', '完成报名时间', '招标控制价(万元)', '服务期限(年)', '开标日期', '招标公司名称', '招标公司对接人', '联系方式', '招投标负责人',
                    '主管院长', '', '主管处(科)长', '', '招标办', '', '内线教练', '', '招投标文件失分项分析', '是否同意投标', '标书申请制作流程', '完成时间', '标书制作人',
                    '标书审核流程', '标段号', '是否中标', '中标单位', '中标价格(万元/年)', '标段号', '投标单位', '投标总价格(万元)', '招标期限(年)', '单年价格(万元/年)', '备注', '',
                ],
            ];
            const tHeader = [
                '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
                '姓名', '电话', '姓名', '电话', '姓名', '电话', '姓名', '电话', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
            ];
            const filterVal = [];// 表头所对应的字段,这里未填写
            const data = this.marketing.list.map(v => filterVal.map(j => v[j]));
            // 进行所有表头的单元格合并
            const merges = [
                'A1:A3', 'B1:O1', 'P1:R1', 'S1:T1', 'U1:AK1', 'AL1:AN1', 'AO1:AR1', 'AS1:AV1', 'AW1:BB1', 'BC1:BC3', 'B2:B3', 'C2:C3', 'D2:D3',
                'E2:E3', 'F2:F3', 'G2:G3', 'H2:H3', 'I2:I3', 'J2:J3', 'K2:K3', 'L2:L3', 'M2:M3', 'N2:N3', 'O2:O3', 'P2:P3', 'Q2:Q3', 'R2:R3', 'S2:S3',
                'T2:T3', 'U2:U3', 'V2:V3', 'W2:W3', 'X2:X3', 'Y2:Y3', 'Z2:Z3', 'AA2:AA3', 'AB2:AB3', 'AC2:AC3', 'AD2:AE2', 'AF2:AG2', 'AH2:AI2',
                'AJ2:AK2', 'AL2:AL3', 'AM2:AM3', 'AN2:AN3', 'AO2:AO3', 'AP2:AP3', 'AQ2:AQ3', 'AR2:AR3', 'AS2:AS3', 'AT2:AT3', 'AU2:AU3', 'AV2:AV3',
                'AW2:AW3', 'AX2:AX3', 'AY2:AY3', 'AZ2:AZ3', 'BA2:BA3', 'BB2:BB3',
            ];

            excel.export_json_to_excel({
                multiHeader, // 这里是第一行的表头
                multiHeader2, // 这里是第二行的表头
                header: tHeader, // 这里是第三行的表头
                data,
                filename: '营销信息列表',
                merges,
            });
        });
    }

表格过长,截取部分,效果如下:
å¨è¿éæå¥å¾çæè¿° 

注意: 

如果只有2行表头,则const multiHeader2 = []

对于const filterVal = [];// 表头所对应的字段,这里未填写。filterVal里记录的是最下面一行表头对应的属性名(字段名)

 

 

Logo

前往低代码交流专区

更多推荐