Export CSV In Javascript

PHP Developer Freelance | E-learning Platform external link
🔗 See other jobs

The snippet below allows you to export your provided data as CSV from your Javascript frontend:


01: <script>
02: const link = document.createElement('a');
03: link.download = `./export_name.csv`;
04: const blob = new Blob(
05:     ['id; name; email;',
06:         '\n',
07:         '1; John Doe; john.doe@acme.com',
08:         '\n',
09:         '2; Jane Doe; jane.doe@acme.com'
10:     ], {
11:         type: 'data:text/csv;charset=utf-8,'
12:     });
13: link.href = URL.createObjectURL(blob);
14: link.click();
15: URL.revokeObjectURL(link.href);
16: </script>

The data is provided as an array on line 4 and then converted to a blob.

An A tag is used to trigger the data export which is created on line 2 and triggered on line 14.

Here is another article you might like 😊 "Simple PHP Templating Engine"