feat: improve Excel export styling with auto column widths, zebra striping, borders, and number formatting

This commit is contained in:
Atharv1705
2026-11-16 10:00:05 +05:30
parent 8ebdd0142c
commit 5d98aa57cb
2 changed files with 162 additions and 12 deletions
@@ -68,6 +68,36 @@ function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
});
const ws = XLSX.utils.json_to_sheet(exportRows);
// Auto-fit column widths with generous padding so text/codes are never truncated
const colWidths = visibleCols.map((col) => {
const headerLabel =
typeof col.columnDef.header === "string" ? col.columnDef.header : col.id;
let maxLen = headerLabel.length;
for (const row of rows) {
const cellVal = formatExcelCell(row.getValue(col.id));
const strVal = String(cellVal ?? "");
if (strVal.length > maxLen) {
maxLen = strVal.length;
}
}
return { wch: Math.min(50, Math.max(14, maxLen + 3)) };
});
ws["!cols"] = colWidths;
// Add comfortable row heights: header row taller (26pt), data rows spacious (20pt)
ws["!rows"] = [
{ hpt: 26 },
...rows.map(() => ({ hpt: 20 })),
];
// Enable native Excel AutoFilter dropdowns on the header row
const lastColLetter = XLSX.utils.encode_col(visibleCols.length - 1);
ws["!autofilter"] = { ref: `A1:${lastColLetter}${rows.length + 1}` };
// Explicitly enable grid lines in Excel view
ws["!views"] = [{ showGridLines: true }];
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Data");
XLSX.writeFile(wb, `${filename}.xlsx`);