FPSMS-frontend
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 

47 rader
1.4 KiB

  1. import * as XLSX from "xlsx";
  2. /**
  3. * Export an array of row objects to a .xlsx file and trigger download.
  4. * @param rows Array of objects (keys become column headers)
  5. * @param filename Download filename (without .xlsx)
  6. * @param sheetName Optional sheet name (default "Sheet1")
  7. */
  8. export function exportChartToXlsx(
  9. rows: Record<string, unknown>[],
  10. filename: string,
  11. sheetName = "Sheet1"
  12. ): void {
  13. if (rows.length === 0) {
  14. const ws = XLSX.utils.aoa_to_sheet([[]]);
  15. const wb = XLSX.utils.book_new();
  16. XLSX.utils.book_append_sheet(wb, ws, sheetName);
  17. XLSX.writeFile(wb, `${filename}.xlsx`);
  18. return;
  19. }
  20. const ws = XLSX.utils.json_to_sheet(rows);
  21. // Auto-set column widths based on header length (simple heuristic).
  22. const header = Object.keys(rows[0] ?? {});
  23. if (header.length > 0) {
  24. ws["!cols"] = header.map((h) => ({
  25. // Basic width: header length + padding, minimum 12
  26. wch: Math.max(12, h.length + 4),
  27. }));
  28. // Make header row look like a header (bold).
  29. header.forEach((_, colIdx) => {
  30. const cellRef = XLSX.utils.encode_cell({ r: 0, c: colIdx });
  31. const cell = ws[cellRef];
  32. if (cell) {
  33. cell.s = {
  34. font: { bold: true },
  35. };
  36. }
  37. });
  38. }
  39. const wb = XLSX.utils.book_new();
  40. XLSX.utils.book_append_sheet(wb, ws, sheetName);
  41. XLSX.writeFile(wb, `${filename}.xlsx`);
  42. }