There might be cases, when you have some data at front-end (via AJAX call , etc.) and you need to create a file for users to download it. CSV is simple format to store tabular data in plain text.
Here we will take a look at saving some data directly from browser. The steps are very simple:
There are certain guidelines that a CSV file needs to follow as specified in RFC4180, but to keep things simple, we will follow these rules:
,
(comma).
1,Timothy,Hamilton,Male,146.205.212.14
3,Terry,Vasquez,Male,119.83.126.89 // Correct
3,Terry,"Vas'qu,ez",Male,119.83.126.89 // This is also correct CSV,
// but the example code may not work
// with such data
1,Timothy,Hamilton,Male,146.205.212.14 \n
2,Jose,Parker,Male,93.159.55.174
3,Terry,Vasquez,Male,119.83.126.89, // Wrong
3,Terry,Vasquez,Male,119.83.126.89 // Correct
Keeping this basic rules in mind, lets begin:
const data = [
[1, 'Timothy', 'Hamilton', 'Male', '146.205.212.14'],
[2, 'Jose', 'Parker', 'Male', '93.159.55.174'],
[3, 'Terry', 'Vasquez', 'Male', '119.83.126.89'],
[4, 'Ruby', 'Rose', 'Female', '124.60.220.96'],
[5, 'Lawrence', 'Henderson', 'Male', '208.165.238.89'],
[6, 'Jeffrey', 'Campbell', 'Male', '235.159.156.1'],
[7, 'Jack', 'Torres', 'Male', '220.147.205.219'],
[8, 'Rachel', 'Stanley', 'Female', '186.17.24.36'],
[9, 'Gregory', 'Pierce', 'Male', '241.176.82.141'],
[10, 'Ronald', 'Hanson', 'Male', '70.93.233.186'],
];
let csvData = '';
data.forEach((row) => {
csvData += '\n';
csvData += row.reduce((prev, col) => `${prev},${col}`, '').slice(1);
});
If you have headers for your data, you can add them. They must follow the same rules as the data.
csvData = 'id,first_name,last_name,gender,ip_address' + csvData;
Now it’s time to create a link/button to down load the CSV File
const hiddenElement = document.createElement('a');
hiddenElement.href = `data:text/csv;charset=utf-8,${encodeURI(csvData)}`;
hiddenElement.target = '_blank';
hiddenElement.download = 'download.csv';
document.body.appendChild(hiddenElement);
hiddenElement.click();
hiddenElement.remove();
Sample code from JSFiddle.