()
| 4 | import { $t } from '@common/locales' |
| 5 | |
| 6 | export const useExcelExport = <T>() => { |
| 7 | const createExcel = (sheetTitle: string, columns: ExcelJS.Column[], tableData: T[]) => { |
| 8 | const workBook = new ExcelJS.Workbook() |
| 9 | const sheet = workBook.addWorksheet(sheetTitle || $t('默认工作表')) |
| 10 | sheet.columns = columns |
| 11 | sheet.addRows(tableData) |
| 12 | return workBook |
| 13 | } |
| 14 | |
| 15 | const exportExcel = async ( |
| 16 | fileTitle: string, |
| 17 | date: [number, number], |
| 18 | sheetTitle: string, |
| 19 | tableId: string, |
| 20 | tableColumnConfig: (ProColumnType<T> & { eoTitle: string })[], |
| 21 | tableData: T[] |
| 22 | ) => { |
| 23 | const workBook = createExcel( |
| 24 | sheetTitle, |
| 25 | getColumns(tableId, tableColumnConfig) as ExcelJS.Column[], |
| 26 | tableData || [] |
| 27 | ) |
| 28 | const fileName = getFileName(fileTitle, date) |
| 29 | try { |
| 30 | const buffer = await workBook.xlsx.writeBuffer() |
| 31 | saveAs( |
| 32 | new Blob([buffer], { |
| 33 | type: 'application/octet-stream' |
| 34 | }), |
| 35 | `${fileName}.xlsx` |
| 36 | ) |
| 37 | } catch (error) { |
| 38 | console.error('Error exporting Excel file:', error) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | const getColumns = (tableId: string, tableColumnConfig: (ProColumnType<T> & { eoTitle: string })[]) => { |
| 43 | let tableConfig: Record<string, { show: boolean }> | null |
| 44 | try { |
| 45 | const storedConfig = localStorage.getItem(tableId) |
| 46 | tableConfig = storedConfig ? JSON.parse(storedConfig) : {} |
| 47 | } catch (error) { |
| 48 | console.error('Error parsing localStorage config:', error) |
| 49 | tableConfig = {} |
| 50 | } |
| 51 | return tableColumnConfig |
| 52 | .filter((head: ProColumnType<T> & { eoTitle: string }) => tableConfig?.[head.dataIndex as string]?.show) |
| 53 | .map((head) => { |
| 54 | return { |
| 55 | header: $t(head.eoTitle), |
| 56 | key: head.dataIndex, |
| 57 | width: (head.eoTitle as string).length > 5 ? (head.eoTitle as string).length * 3 : 15, |
| 58 | style: (head.dataIndex as string).includes('Rate') ? { numFmt: '0.00%' } : undefined |
| 59 | } |
| 60 | }) |
| 61 | } |
| 62 | |
| 63 | const getFileName = (fileTitle: string, date: [number, number]): string => { |
no outgoing calls
no test coverage detected