Last active
April 16, 2026 21:11
-
-
Save panzi/8bb74b439ea01e745dbdaccfa8cbb043 to your computer and use it in GitHub Desktop.
Minimal function to save a CSV from memory in browser JavaScript. Consider this code as public domain, since it's trivial.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function escapeCSV(value: string): string { | |
| if (/^[-+._=\/a-z0-9]*$/i.test(value)) { | |
| return value; | |
| } | |
| return `"${value.replace(/"/g, '""')}"`; | |
| } | |
| export function buildCSV(data: string[][]): string { | |
| const buf: string[] = ['\ufeff']; // BOM | |
| for (const row of data) { | |
| if (row.length > 0) { | |
| buf.push(escapeCSV(row[0])); | |
| for (let index = 1; index < row.length; ++ index) { | |
| buf.push(',', escapeCSV(row[index])); | |
| } | |
| } | |
| buf.push('\r\n'); | |
| } | |
| return buf.join(''); | |
| } | |
| export function downloadCSV(filename: string, data: string[][]): void { | |
| const blob = new Blob([buildCSV(data)], { type: 'text/csv' }); | |
| const url = URL.createObjectURL(blob); | |
| const link = document.createElement('a'); | |
| link.download = filename; | |
| link.href = url; | |
| link.style.opacity = '0'; | |
| link.style.position = 'fixed'; | |
| link.style.right = '0'; | |
| link.style.bottom = '0'; | |
| document.body.appendChild(link); | |
| link.click(); | |
| setTimeout(() => { | |
| URL.revokeObjectURL(url); | |
| link.parentNode?.removeChild(link); | |
| }, 0); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment