項目中遇到了動態(tài)合并單元格的復(fù)雜表格,用XLSX的book_append_sheet方法還得動態(tài)計算合并單元格的信息,太麻煩了。好在這個表格沒有分頁,無需再次從接口中請求數(shù)據(jù),直接可導(dǎo)出。百度了很久,發(fā)現(xiàn)了XLSX的另一個方法:table_to_book
1、首先安裝依賴
npm i xlsx
npm i file-saver
2、引入依賴
import * as XLSX from 'xlsx'
import {saveAs} from 'file-saver'
3、給要導(dǎo)出的表格元素添加id屬性
<div id="tj-summary-table">
<n-data-table
id="summaryTable1"
:columns="columns"
:data="tableData"
:pagination="false"
:single-line="false"
:summary="summary"
:row-class-name="rowClassName"
></n-data-table>
</div>

image.png
4、導(dǎo)出方法
function exportTable() {
const table = document.getElementById('summaryTable1')
if (table) exportExcel(`${props.year}年探井部署年度計劃`, table)
}
//非常方便的表格導(dǎo)出功能,直接傳入表格對應(yīng)的HTMLElement即可,合并的單元格會直接保留,僅支持單sheet,僅支持導(dǎo)出展示的表格頁
function exportExcel(fileName:string,tableElement:HTMLElement){
const wb = XLSX.utils.table_to_book(tableElement, {raw:true})
const wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST:true, type: 'array'})
saveAs( new Blob([wbout],{type: 'application/octet-stream'}),`${fileName}.xlsx`)
}
5、效果展示

image.png