28 lines
743 B
TypeScript
28 lines
743 B
TypeScript
export function generateCsv(
|
|
rows: Record<string, any>[],
|
|
columns: { key: string; header: string }[],
|
|
): string {
|
|
const headerLine = columns
|
|
.map((c) => `"${c.header.replace(/"/g, '""')}"`)
|
|
.join(",");
|
|
const lines = rows.map((row) => {
|
|
return columns
|
|
.map((c) => {
|
|
let val = row[c.key];
|
|
if (val === null || val === undefined) {
|
|
return '""';
|
|
}
|
|
if (typeof val === "object") {
|
|
if (val instanceof Date) {
|
|
val = val.toISOString();
|
|
} else {
|
|
val = JSON.stringify(val);
|
|
}
|
|
}
|
|
return `"${String(val).replace(/"/g, '""')}"`;
|
|
})
|
|
.join(",");
|
|
});
|
|
return "\uFEFF" + [headerLine, ...lines].join("\r\n");
|
|
}
|