Skip to content

Instantly share code, notes, and snippets.

@scriptex
Last active January 14, 2021 21:53
Show Gist options
  • Save scriptex/a4440371cb6e06e78381c055c8072761 to your computer and use it in GitHub Desktop.
Save scriptex/a4440371cb6e06e78381c055c8072761 to your computer and use it in GitHub Desktop.
Export to CSV from JavaScript
type ValuesOf<T extends any[]> = T[number];
type IndexedList<T> = Record<string, T>;
const exportCSV = <T>(data: Array<IndexedList<ValuesOf<T[]>>>, keys: string[], columns: string[]): string => {
let csv = 'data:text/csv;charset=utf-8,';
columns.forEach((column: string) => {
csv += `${column},`;
});
csv += '\r\n';
data.forEach((item: IndexedList<ValuesOf<T[]>>) => {
keys.forEach((key: string) => {
csv += `${item[key]},`;
});
csv += '\r\n';
});
return encodeURI(csv);
};
// Usage
const keysSample: string[] = ['index', 'name', 'id', 'status'];
const columnsSample: string[] = ['No.', 'Name', 'ID', 'Status'];
const dataSample: Array<IndexedList<ValuesOf<typeof keysSample>>> = [
{
index: '1',
name: 'Test 1',
id: 'ID1',
status: 'active'
},
{
index: '2',
name: 'Test 2',
id: 'ID2',
status: 'inactive'
}
];
const link = document.createElement('a');
link.setAttribute('href', exportCSV<string>(dataSample, keysSample, columnsSample));
link.setAttribute('download', 'export.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment