fix(web-admin): 月度样本总览导出表头居中 (#195)

改用 ExcelJS 导出,列头水平垂直居中,并保留已设定列宽。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zlwuandCursor committed 2026-12-03 11:58:58 +08:00
1 parent ad9f4ae785
commit 68be4e57db
1 file changed
+33 -21
@@ -111,7 +111,6 @@
<script setup lang="ts">
import { Download, RefreshLeft, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import {
fetchMonthlySampleOverviewList,
type MonthlySampleOverviewRow
@@ -218,19 +217,6 @@
loadData()
}
function buildExportRows(rows: MonthlySampleOverviewRow[]) {
const headers = ['序号', ...columns.map((c) => c.label)]
const sheetRows = rows.map((row, idx) => {
const line: Record<string, string | number> = { 序号: idx + 1 }
columns.forEach((c) => {
const v = row[c.prop as keyof MonthlySampleOverviewRow]
line[c.label] = v === null || v === undefined || v === '' ? '' : String(v)
})
return line
})
return { headers, sheetRows }
}
async function fetchAllFilteredRows() {
const pageSize = 200
let page = 1
@@ -248,6 +234,38 @@
return rows
}
async function writeExcelFile(rows: MonthlySampleOverviewRow[], filename: string) {
const ExcelJS = (await import('exceljs')).default
const workbook = new ExcelJS.Workbook()
const sheet = workbook.addWorksheet('月度样本信息总览')
const headers = ['序号', ...columns.map((c) => c.label)]
sheet.addRow(headers)
rows.forEach((row, idx) => {
sheet.addRow([
idx + 1,
...columns.map((c) => {
const v = row[c.prop as keyof MonthlySampleOverviewRow]
return v === null || v === undefined || v === '' ? '' : String(v)
})
])
})
sheet.columns = [{ width: 8 }, ...columns.map((c) => ({ width: c.exportWch }))]
const headerRow = sheet.getRow(1)
headerRow.font = { bold: true }
headerRow.eachCell((cell) => {
cell.alignment = { horizontal: 'center', vertical: 'middle' }
})
const buffer = await workbook.xlsx.writeBuffer()
const blob = new Blob([buffer], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = filename
a.click()
URL.revokeObjectURL(a.href)
}
async function handleExport() {
if (!canExport.value) {
ElMessage.warning('无导出权限')
@@ -261,15 +279,9 @@
ElMessage.warning(useSelected ? '请先勾选要导出的记录' : '当前筛选无数据可导出')
return
}
const { headers, sheetRows } = buildExportRows(rows)
const sheet = XLSX.utils.json_to_sheet(sheetRows, { header: headers })
// 序号 + 业务列:给够可读宽度,避免 Excel 默认挤在一起
sheet['!cols'] = [{ wch: 8 }, ...columns.map((c) => ({ wch: c.exportWch }))]
const workbook = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(workbook, sheet, '月度样本信息总览')
const stamp = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '')
const suffix = useSelected ? `已选${rows.length}条_` : ''
XLSX.writeFile(workbook, `月度样本信息总览_${suffix}${stamp}.xlsx`)
await writeExcelFile(rows, `月度样本信息总览_${suffix}${stamp}.xlsx`)
} catch (e: any) {
ElMessage.error(e?.message || '导出失败')
} finally {