基于 xlsx-js-style 的 Excel 导出工具实现导出excel
基于 xlsx-js-style 的 Excel 导出工具实现
🎯 项目背景
在后台管理系统中,数据导出功能是必不可少的需求。用户经常需要将表格数据导出为 Excel 文件进行离线查看、数据分析和报表制作。为了提供更好的用户体验,我们需要一个功能完善、易于使用的 Excel 导出工具。
为什么选择 xlsx-js-style?
- 功能完整:支持样式设置、格式控制等高级功能
- 性能优秀:基于 SheetJS 核心库,性能稳定
- API 友好:提供简洁易用的 API 接口
- 浏览器兼容:支持主流浏览器,无需额外配置
- 样式支持:支持单元格样式、边框、字体等设置
安装依赖
npm install xlsx-js-style
工具函数结构
import XLSX from 'xlsx-js-style'
import { newTime } from './tool'/*** 导出数据到 Excel 文件* @description 将数据数组导出为 Excel 文件,支持自定义表头和样式* @param {any[]} dataList - 要导出的数据数组* @param {string[]} fields - 字段名数组,指定要导出的列* @param {string[]} [headers=[]] - 表头数组,可选参数* @param {string} [fileName='Excel'] - 文件名,可选参数* @param {string} [sheetName='Sheet'] - 工作表名称,可选参数* @returns {void} 无返回值,直接下载文件* @example* ```typescript* const data = [{id: 1, name: '张三'}, {id: 2, name: '李四'}]* exportExcel(data, ['id', 'name'], ['编号', '姓名'], '员工信息')* ```*/
export let exportExcel = (dataList: any, fields: Array<string>, headers: Array<string> = [], fileName: string = 'Excel', sheetName: string = 'Sheet') => {let data = new Array()if (!Array.isArray(dataList)) return console.warn('dataList is not an array type')data = dataList.map((obj) => {return fields.map((field) => {return obj[field]})})if (headers.length > 0) {data.splice(0, 0, headers)} else {// 将headers设置为英文字段表头data.splice(0, 0, fields)}const ws = XLSX.utils.aoa_to_sheet(data) // 创建工作表const wb: any = XLSX.utils.book_new() // 创建工作簿let arr: any = []headers.forEach((val: any) => {arr.push({wpx: 120})})ws["!cols"] = arr// 设置内容居中// 设置单元格公共样式let borderAll = { //单元格外侧框线top: {style: 'thin',},bottom: {style: 'thin',},left: {style: 'thin',},right: {style: 'thin',}}for (let key in ws) {// 单元格公共样式设置if (ws[key] instanceof Object) {ws[key].s = {// border: borderAll,alignment: {horizontal: 'center',vertical: 'center',// wrapText: 1,//自动换行},// fill: { //背景色// fgColor: { rgb: 'dbf3f2' }// },font: {sz: 13,//单元格中字体的样式与颜色设置color: {rgb: '000000'}},// bold: true,numFmt: 0}}}// console.log(fields,'fields')// 隐藏表头// let wsrows = [{ hidden: true }]// ws['!rows'] = wsrows // ws - wsXLSX.utils.book_append_sheet(wb, ws, sheetName) // 将工作表添加到工作簿中XLSX.writeFile(wb, fileName + newTime() + '.xlsx') // 导出文件
}
数据处理流程
- 数据验证:检查输入数据是否为数组类型
- 数据转换:将对象数组转换为二维数组格式
- 表头处理:支持自定义表头或使用字段名作为表头
- 样式设置:应用统一的单元格样式
- 文件生成:创建并下载 Excel 文件
✨ 功能特性
1. 灵活的数据处理
- 支持任意对象数组作为输入
- 自动提取指定字段
- 支持自定义表头显示
2. 丰富的样式设置
- 单元格居中对齐
- 自定义字体大小和颜色
- 统一的边框样式
- 自动列宽调整
3. 用户友好的配置
- 可选参数支持默认值
- 自动文件命名(添加时间戳)
- 支持自定义工作表名称
4. 错误处理
- 输入数据验证
- 友好的错误提示
- 防止文件重名冲突
📖 使用指南
基础用法
// 准备数据
const employeeData = [{ id: 1, name: '张三', age: 25, department: '技术部', salary: 8000 },{ id: 2, name: '李四', age: 30, department: '销售部', salary: 9000 },{ id: 3, name: '王五', age: 28, department: '人事部', salary: 7500 }
]// 定义字段和表头
const fields = ['id', 'name', 'age', 'department', 'salary']
const headers = ['员工编号', '姓名', '年龄', '部门', '薪资']// 导出 Excel
exportExcel(employeeData, fields, headers, '员工信息表', '员工数据')
高级用法
// 只导出部分字段
const selectedFields = ['name', 'department', 'salary']
const selectedHeaders = ['姓名', '部门', '薪资']exportExcel(employeeData, selectedFields, selectedHeaders, '员工薪资表')// 使用英文字段名作为表头
exportExcel(employeeData, ['id', 'name', 'age'], [], 'Employee List')
在 Vue 组件中使用
<template><div><a-button @click="exportEmployeeData" type="primary">导出员工数据</a-button></div>
</template><script setup lang="ts">
import { exportExcel } from '@/utils/exxlsx'
import { message } from 'ant-design-vue'const employeeData = ref([{ id: 1, name: '张三', age: 25, department: '技术部' },{ id: 2, name: '李四', age: 30, department: '销售部' }
])const exportEmployeeData = () => {try {const fields = ['id', 'name', 'age', 'department']const headers = ['编号', '姓名', '年龄', '部门']exportExcel(employeeData.value, fields, headers, '员工信息')message.success('导出成功!')} catch (error) {message.error('导出失败,请重试')console.error('导出错误:', error)}
}
</script>
🎨 样式定制
自定义样式配置
// 在 exportExcel 函数中可以自定义样式
const customStyles = {alignment: {horizontal: 'center',vertical: 'center'},font: {sz: 14,color: { rgb: '333333' },bold: true},fill: {fgColor: { rgb: 'f0f0f0' }},border: {top: { style: 'thin' },bottom: { style: 'thin' },left: { style: 'thin' },right: { style: 'thin' }}
}
🚀 最佳实践
1. 数据预处理
// 在导出前对数据进行格式化
const formatData = (data: any[]) => {return data.map(item => ({...item,salary: `¥${item.salary.toLocaleString()}`,age: `${item.age}岁`,department: item.department || '未分配'}))
}// 使用格式化后的数据导出
const formattedData = formatData(employeeData)
exportExcel(formattedData, fields, headers, '员工信息')
2. 错误处理
const safeExport = (data: any[], fields: string[], headers: string[]) => {try {if (!Array.isArray(data) || data.length === 0) {throw new Error('数据为空或格式不正确')}if (fields.length === 0) {throw new Error('请指定要导出的字段')}exportExcel(data, fields, headers, '数据导出')return true} catch (error) {console.error('导出失败:', error)return false}
}