Initial commit - Horux Despachos NL
This commit is contained in:
30
apps/web/lib/export-excel.ts
Normal file
30
apps/web/lib/export-excel.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import * as XLSX from 'xlsx';
|
||||
import { saveAs } from 'file-saver';
|
||||
|
||||
interface ExcelColumn {
|
||||
header: string;
|
||||
key: string;
|
||||
width?: number;
|
||||
}
|
||||
|
||||
export function exportToExcel(
|
||||
data: Record<string, any>[],
|
||||
columns: ExcelColumn[],
|
||||
filename: string,
|
||||
) {
|
||||
const rows = data.map((row) =>
|
||||
Object.fromEntries(columns.map((col) => [col.header, row[col.key] ?? '']))
|
||||
);
|
||||
|
||||
const ws = XLSX.utils.json_to_sheet(rows);
|
||||
|
||||
// Aplicar anchos de columna
|
||||
ws['!cols'] = columns.map((col) => ({ wch: col.width || 15 }));
|
||||
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'Datos');
|
||||
|
||||
const buf = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
|
||||
const blob = new Blob([buf], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||
saveAs(blob, `${filename}.xlsx`);
|
||||
}
|
||||
Reference in New Issue
Block a user