import * as XLSX from "xlsx"; /** * Export an array of row objects to a .xlsx file and trigger download. * @param rows Array of objects (keys become column headers) * @param filename Download filename (without .xlsx) * @param sheetName Optional sheet name (default "Sheet1") */ export function exportChartToXlsx( rows: Record[], filename: string, sheetName = "Sheet1" ): void { if (rows.length === 0) { const ws = XLSX.utils.aoa_to_sheet([[]]); const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, sheetName); XLSX.writeFile(wb, `${filename}.xlsx`); return; } const ws = XLSX.utils.json_to_sheet(rows); // Auto-set column widths based on header length (simple heuristic). const header = Object.keys(rows[0] ?? {}); if (header.length > 0) { ws["!cols"] = header.map((h) => ({ // Basic width: header length + padding, minimum 12 wch: Math.max(12, h.length + 4), })); // Make header row look like a header (bold). header.forEach((_, colIdx) => { const cellRef = XLSX.utils.encode_cell({ r: 0, c: colIdx }); const cell = ws[cellRef]; if (cell) { cell.s = { font: { bold: true }, }; } }); } const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, sheetName); XLSX.writeFile(wb, `${filename}.xlsx`); }