使用 Exceljs 時,輸出時常會遇上一個需求 – 動態調整欄寬,以讓打開時可以顯示完整內容。這邊筆記下實現方法。
內容
官方沒有給出明確的參數可調,但可透過遍歷每張 worksheet 的 column 來調。
一個 workbook 內可以有多個 worksheet。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import Exceljs from 'exceljs' /** * Autofit columns by width * * @param worksheet - Exceljs Worksheet * @param minimalWidth - Minimal width for each column * @param padding - Extra width added for aesthetics and spacing */ const autoColumnWidth = ({ worksheet, minimalWidth = 10, padding = 4, }: { worksheet: Exceljs.Worksheet minimalWidth?: number padding?: number }) => { worksheet.columns.forEach((column) => { let maxColumnLength = 0 if (column && column.eachCell) { column.eachCell({ includeEmpty: true }, (cell) => { // 獲取儲存格值的長度,如果為空值則長度為 0 const cellValueLength = String(cell.value || '').length // 更新最大長度 maxColumnLength = Math.max(maxColumnLength, minimalWidth, cellValueLength) }) // 設定欄位寬度:最大長度 + 額外間距 column.width = maxColumnLength + padding } }) } |

