前言
先看下最终效果图吧,需要的可以参考我的实现方式
这是最终导出的表格文件
类似这种的,特定单元格需要额外标注,表头也有月份然后细分的,表格组件是这样的
注意
别使用xlsx-style 这个库,太多问题了,按照网上的教程改了源码都不行,哈哈,然后选择xlsx-style-vite这个库,一点问题没有了。
import * as XLSX from 'xlsx'
import * as XLSX_STYLE from 'xlsx-style-vite'
import * as FileSaver from 'file-saver'
实现
这里贴一下主要实现代码吧
// 导出 Excel 的方法
const exportExcel = async () => {LoadBtn.value = trueconst elementTable = tabRef.valuelet worksheet = XLSX.utils.table_to_sheet(elementTable.$el)const workbook = XLSX.utils.book_new()setPubExcel(worksheet)XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')let wbout = XLSX_STYLE.write(workbook, { bookType: 'xlsx', bookSST: false, type: 'binary' })FileSaver.saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream;charset=utf-8"' }),'xx项目汇总统计' + dayjs().format('YYYYMMDD') + '.xlsx')// 导出 Excel 文件// XLSX.writeFile(workbook, 'table.xlsx')
}//设置公共样式
const setPubExcel = (data: any) => {data['!cols'] = [{ wpx: 60 },{ wpx: 200 },{ wpx: 60 },{ wpx: 400 },{ wpx: 90 },{ wpx: 80 },{ wpx: 80 },{ wpx: 100 },{ wpx: 100 },{ wpx: 70 },{ wpx: 70 },{ wpx: 70 },{ wpx: 600 },{ wpx: 200 }]const excludes = ['!cols', '!fullref', '!merges', '!ref', '!rows']for (let key in data) {if (data?.hasOwnProperty(key)) {// if (!excludes.includes(key)) {// console.log(key, 'key', data[key], 'value-------')if (key[0] === 'G' || key[0] === 'F') {// console.log('时间', data[key], '-----', key)const v = data[key].vif (!v || v === '') continue// console.log('after-time', formatExcelDate(v))let time = formatExcelDate(v)// 判断是否小于当前时间if (dayjs().isAfter(time)) {data[key].s = {// border: {// top: { style: 'thin', color: { rgb: '000000' } },// bottom: { style: 'thin', color: { rgb: '000000' } },// left: { style: 'thin', color: { rgb: '000000' } },// right: { style: 'thin', color: { rgb: '000000' } }// },// alignment: {// horizontal: 'center', //水平居中对齐// vertical: 'center', //垂直居中// wrapText: true //是否换行// },fill: {fgColor: { rgb: 'FFFF0000' } // 设置标题单元格的背景颜色}}}}}}
}const s2ab = (s: any) => {const buf = new ArrayBuffer(s.length)const view = new Uint8Array(buf)for (let i = 0; i < s.length; i++) {view[i] = s.charCodeAt(i) & 0xff}return buf
}// 表格特定的时间转换
function formatExcelDate(numb: number, format = '/') {const time = new Date((numb - 25569) * 24 * 3600000)return time.toLocaleDateString('zh-CN', {year: 'numeric',month: '2-digit',day: '2-digit'}).replace(/\//g, format)
}
end
希望对你有帮助,点个赞吧!