【纯前端excel导出】vue2纯前端导出excel,使用xlsx插件,修改样式、合并单元格

时间:2024-10-16 18:44:56

一、使用第三方插件

1、安装

npm install xlsx-js-style

2、引入

import xlsx from 'xlsx-js-style'

 

xlsx插件是基础的导出,不可以修改样式,直接xlsx-style插件式修改样式的,所以这里直接用二者合体插件即可

二、页面使用

1、数据源

[
  {"rectifyPresideName": "朱佳佳","accepUser": "张红艳","rectifyCompleteTime": "2024-09-27 10:17:43","checkTableType": "重点时段及节假日前排查","rectifyTerm": "2024-09-27 23:59:59","rectifyDeptName": "炭黑厂炭黑车间","rectifyPlan": "建立使用记录","faultName": "岗位急救箱无使用记录","createDate": "2024年09月27日"},
  {"rectifyPresideName": "崔国梁","accepUser": "崔国梁","rectifyCompleteTime": "2024-09-26 17:13:05","checkTableType": "重点时段及节假日前排查","rectifyTerm": "2024-09-26 23:59:59","rectifyDeptName": "焦化厂第三干熄焦车间","rectifyPlan": "更换或检查修复","faultName": "疏散指示灯不亮","createDate": "2024年09月26日"},
  {"rectifyPresideName": "贾成成","accepUser": "贾成成","rectifyCompleteTime": "2024-09-26 17:23:12","checkTableType": "重点时段及节假日前排查","rectifyTerm": "2024-09-26 23:59:59","rectifyDeptName": "甲醇厂公辅车间","rectifyPlan": "安排岗位人员更换消防抢","faultName": "消防水枪损坏","createDate": "2024年09月26日"},
  {"rectifyPresideName": "王小娟","accepUser": "李学红","rectifyCompleteTime": "2024-09-25 16:50:45","checkTableType": "重点时段及节假日前排查","rectifyTerm": "2024-09-25 23:59:59","rectifyDeptName": "苯精制厂","rectifyPlan": "安装阀门","faultName": "萃取塔回流罐液位计排污阀为单阀","createDate": "2024年09月24日"}
]

2、将数据源转成需要的二维数组

const data = res.data.data.map((ele, i) => ({
          xuhao: i + 1,
          faultName: ele.faultName,
          createDate: ele.createDate,
          checkTableType: ele.checkTableType,
          rectifyPlan: ele.rectifyPlan,
          rectifyDeptName: ele.rectifyDeptName,
          rectifyPresideName: ele.rectifyPresideName,
          rectifyTerm: ele.rectifyTerm,
          rectifyCompleteTime: ele.rectifyCompleteTime,
          accepUser: ele.accepUser,
}))
const body = data.map((x) => [x.xuhao,x.faultName,x.createDate,x.checkTableType,x.rectifyPlan,x.rectifyDeptName,x.rectifyPresideName,x.rectifyTerm,x.rectifyCompleteTime,x.accepUser,])

// 转换后的二维数据
[
  [1,"岗位急救箱无使用记录","2024年09月27日","重点时段及节假日前排查","建立使用记录","炭黑厂炭黑车间","朱佳佳","2024-09-27 23:59:59","2024-09-27 10:17:43","张红艳"],
  [2,"疏散指示灯不亮","2024年09月26日","重点时段及节假日前排查","更换或检查修复","焦化厂第三干熄焦车间","崔国梁","2024-09-26 23:59:59","2024-09-26 17:13:05","崔国梁"],
  [3,"消防水枪损坏","2024年09月26日","重点时段及节假日前排查","安排岗位人员更换消防抢","甲醇厂公辅车间","贾成成","2024-09-26 23:59:59","2024-09-26 17:23:12","贾成成"],
  [4,"萃取塔回流罐液位计排污阀为单阀","2024年09月24日","重点时段及节假日前排查","安装阀门","苯精制厂","王小娟","2024-09-25 23:59:59","2024-09-25 16:50:45","李学红"]
]

3、定义表头

// 定义Excel表头
 const header = [
   ['隐患排查治理台账'],
   ['序号','问题点','检查时间','检查类别','整改措施','责任单位','责任人','整改时间','','验收人',],
   ['', '', '', '', '', '', '', '计划完成时间', '实际完成时间', ''],]

4、将定义好的表头添加到 body 中

body.unshift(...header) 

5、创建虚拟的 workbook

const workbook = xlsx.utils.book_new()

6、aoa_to_sheet 将二维数组转成 sheet

先写到这儿,明天再写,下班,886~