There is a lot of info on how to create a CSV file with Javascript here on Stack Overflow. But I'm struggling to find a way to create semicolon separated data and be able to set the file name on download.
Below is a simplified version of my code. The last lines demonstrates the problem: CSV with colon works well. CSV with semi colon fails, the browser will not download the file (Chrome says "network error").
const arrayToCsvFile = (dataArray, delimiter, filename) => {
const csv = createCsv(dataArray, delimiter);
exportCsvToFile(csv, filename, delimiter);
};
const createCsv = (rows, delimiter) => {
let returnStr = "";
rows.forEach(row => {
row.forEach(field => {
returnStr += field + delimiter;
});
returnStr += "\r\n";
});
return returnStr;
};
const exportCsvToFile = (csvData, filename, delimiter) => {
csvData = "data:text/csv;charset=utf-8" + delimiter + csvData;
const encodedUri = encodeURI(csvData);
// Trick to set filename
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", filename);
document.body.appendChild(link); // Required for Firefox(?)
link.click();
};
const testData = [["a", "b", "c"], ["1", "2", "3"]];
// Line below works
// arrayToCsvFile(testData, ",", "myCustomFileNameWithCommaSep.csv");
// This does not work - browser fails to download file.
arrayToCsvFile(testData, ";", "myCustomFileNameWithSemiSep.csv");
unparsefunction to generate CSV from a JavaScript data structure).