UNPKG

@pilag6/csv-downloader

Version:

Lightweight CSV export utility for Vue and React

31 lines (30 loc) 764 B
// src/index.ts function downloadCSV({ headers, contents, filename = "data.csv", separator = ",", bom = true }) { const escape = (val) => `"${String(val).replace(/"/g, '""')}"`; const csvRows = [ headers.map(escape).join(separator), ...contents.map((row) => row.map(escape).join(separator)) ]; let csvContent = csvRows.join("\n"); if (bom) { csvContent = "\uFEFF" + csvContent; } const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = filename; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); } export { downloadCSV };