JavaScript之Excel导出


我使用的是这三个插件

<script src="https://cdn.bootcdn.net/ajax/libs/exceljs/4.3.0/exceljs.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/Mock.js/1.0.0/mock-min.js"></script>

(1)生成批量数据

var modata = Mock.mock({
    "tableData|9999":[{
        "name":"@cname","date":"@date","address":"@city(true)"
    }]
});

(2)Excel的头部数据

var data = {
    tableHeader: [
        {
            prop: 'date',
            label: '日期'
        },
        {
            prop: 'name',
            label: '姓名'
        },
        {
            prop: 'address',
            label: '地址'
        }
    ],
    tableData: modata.tableData
};

(3)Excel内容渲染

var workbook = new ExcelJS.Workbook();
workbook.creator = 'Me';
workbook.lastModifiedBy = 'Her';
workbook.created = new Date(1985, 8, 30);
workbook.modified = new Date();
workbook.lastPrinted = new Date(2016, 9, 27);

// 创建带有红色标签颜色的工作表
var sheet = workbook.addWorksheet('MySheet', {properties: {tabColor: {argb: 'FFC0000'}}});
sheet.mergeCells('A1:C1');
sheet.getCell('A1').value = '这是文档正标题';
sheet.getCell('A1').font = {
    name: 'Comic Sans MS',
    family: 4,
    size: 36,
    bold: true
};
sheet.getCell('A1').alignment = { vertical: 'middle', horizontal: 'center' };
sheet.columns = [
    { width: 31 },
    { width: 32 },
    { width: 33 }
];

// 生成columns
var columns = [];
data.tableHeader.map(item => {
    columns.push({
        name: item.label
    })
})

// 生成rows
let rows = [];
data.tableData.map(item => {
    let arr = [];
    data.tableHeader.map(sub => {
        arr.push(item[sub.prop] ? item[sub.prop] : '')
    })
    rows.push(arr);
})

sheet.addTable({
    name: 'MyTestTable',
    ref: 'A2', // 表格左上角的位置
    headerRow: true,
    totalsRow: false,
    style: {
        theme: 'TableStyleLight1',
        showRowStripes: true, //单双行
    },
    columns: columns,
    rows: rows,
});

(4)渲染Excel并导出

workbook.xlsx.writeBuffer().then(buffer => {
    saveAs(new Blob([buffer], {type: 'application/octet-stream'}), '表格导出.xlsx');
});
运行效果

源代码分享
参考文档