Skip to content

Instantly share code, notes, and snippets.

@dhunmoon
Created March 22, 2017 09:57
Show Gist options
  • Save dhunmoon/d743b327c673b589e7acfcbc5633ff4b to your computer and use it in GitHub Desktop.
Save dhunmoon/d743b327c673b589e7acfcbc5633ff4b to your computer and use it in GitHub Desktop.
JS: CSV File Creation Using BLOB
function exportToCsv(filename, rows) {
var processRow = function (row) {
var finalVal = '';
for (var j = 0; j < row.length; j++) {
var innerValue = row[j] === null ? '' : row[j].toString();
if (row[j] instanceof Date) {
innerValue = row[j].toLocaleString();
};
var result = innerValue.replace(/"/g, '""');
if (result.search(/("|,|\n)/g) >= 0)
result = '"' + result + '"';
if (j > 0)
finalVal += ',';
finalVal += result;
}
return finalVal + '\n';
};
var csvFile = '';
for (var i = 0; i < rows.length; i++) {
csvFile += processRow(rows[i]);
}
var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
@shanike
Copy link

shanike commented Aug 3, 2022

I created a csv from an object like this:

const csvData = data.reduce((prev, curr) => (prev += Object.values(curr).join(Delimiter) + "\n"), "");

const Delimiter = ","
and csvData is an array of objects.

You need to add headers too,
and then join csvData with csvHeaders with a delimiter.

const csv = `${csvHeaders}\n${csvData}`;

csvHeaders can be Object.keys(data[0]).join(Delimiter);

@leegee
Copy link

leegee commented Oct 5, 2022

Don't forget to call URL.revokeObjectURL at the end.

@gaalha
Copy link

gaalha commented Jun 6, 2023

Don't forget to call URL.revokeObjectURL at the end.

Why?

@leegee
Copy link

leegee commented Jun 7, 2023

revokeObjectURL

Memory management is a thing.

https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL_static

"Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment