1、安装依赖
npm install xlsx-js-style
2、复制代码文件exportExcel.js至工程
https://github.com/EnthuDai/export-excel-in-one-line
3、在引入excel.js后调用
Excel.export(columns, dataSource, '导出文件名')
4、代码demo
5、效果
页面 | excel |
---|---|
![]() |
![]() |
对于使用vue ant-design 组件库中table组件的场景,可直接将table的 columns 和 data-source、 导出文件名称 作为参数传入export方法,调用即可导出相同格式的excel文件。
Excel.export(this.demoColumn, this.demoData, '测试数据')
对于其他场景,需要对数据格式适配至ant-design table相同格式,具体为:
如:
[
{title:'类别',dataIndex:'type'},
{title:'总计',children:[
{title:'销量',children:[
{title:'今天', dataIndex:'today'},
{title:'昨天', dataIndex:'yesterday'}]
}
]
},
{title:'趋势',children:[
{title:'上涨率',dataIndex:'raise'},
{title:'上涨金额', dataIndex:'raiseAmount'}
]
}
]
如:
[
{type:'笔', today:100, yesterday: 200, raise:'20%', raiseAmount:20, children:[
{type:'毛笔',today:50, yesterday: 100, raise:'20%', raiseAmount:10},
{type:'钢笔',today:50, yesterday: 100, raise:'20%', raiseAmount:10}
]},
{type:'墨', today:100, yesterday: 200, raise:'20%', raiseAmount:20},
{type:'纸', today:100, yesterday: 200, raise:'20%', raiseAmount:20},
{type:'砚', today:100, yesterday: 200, raise:'20%', raiseAmount:20},
]
原理基本参考了使用xlsx.js导出有复杂表头的excel这篇文章,其该文合并表头方法doMerges 存在bug,实测中会出现问题。所以该组件中使用了树中递归处理的算法计算合并项,解决问题的同时也提高了代码的简洁程度。
实现过程:
无children的叶子节点
{title:'类别',dataIndex:'type'}
在数组左上角第一项填入 title,合并单元格时需要向下合并所有单元格,记录下合并的起始和终点项的偏移量 {s:{r:0,c:0},e:{r:0,c:2}}
{
title:'总计',children:[
{title:'销量',children:[
{title:'今天', dataIndex:'today'},
{title:'昨天', dataIndex:'yesterday'}]
}
]
}
在二维数组剩余的部分(红框区域)中,左上角第一项填入title,并记录下横向合并的起终点偏移量,横向合并的数目为该项的children数组中所有节点的叶节点总数。
然后对 向下的剩余部分(绿框区域)递归操作。
https://github.com/EnthuDai/export-excel-in-one-line
如果该内容对你有帮助,帮忙star一下项目呀