Skip to content

Instantly share code, notes, and snippets.

@chris-burkhardt
Last active October 28, 2021 06:31
Show Gist options
  • Save chris-burkhardt/14ba0e3a37c2cef83eaea79e8c93092d to your computer and use it in GitHub Desktop.
Save chris-burkhardt/14ba0e3a37c2cef83eaea79e8c93092d to your computer and use it in GitHub Desktop.
Export CSV File - React/Javascript
import { zipObject } from 'lodash';
export const CSVExport = csvData => {
const { items, headers, filename } = csvData;
// use headers if available, if not, use the key names for headers
// updated to create same type with zipped object
const headerKeys = Object.keys(items[0]);
const rowHeader = headers || zipObject(headerKeys, headerKeys);
const rows = [rowHeader, ...items];
const csv = convertRowsToCSV(rows);
const csvFileName = filename + '.csv' || 'export.csv';
initiateDownload(csv, csvFileName);
};
const convertRowsToCSV = rowData => {
return rowData.map(data => Object.values(data).join(',')).join('\r\n');
};
const initiateDownload = (csvData, csvFileName) => {
const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, csvFileName); // IE 10+
} else {
const link = document.createElement('a');
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', csvFileName);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
};
// example headers object
const headers = {
serviceStartDate: 'Service Start Date',
serviceStartTime: 'Service Start Time',
serviceEndTime: 'Service End Time',
client: 'Client',
service: 'Service',
quantity: 'Quantity',
}
// example items array
const items= [
{
"serviceStartDate": "08 Feb 2020",
"serviceStartTime": "6:30 PM",
"serviceEndTime": "7:30 PM",
"client": "TestClient1",
"service": "Programming",
"quantity": 1,
},
{
"serviceStartDate": "08 Feb 2020",
"serviceStartTime": "9:30 PM",
"serviceEndTime": "11 PM",
"client": "TestClient2",
"service": "Consultation",
"quantity": 1.5,
},
{
"serviceStartDate": "09 Feb 2020",
"serviceStartTime": "1:30 AM",
"serviceEndTime": "2 AM",
"client": "TestClient3",
"service": "Refactoring",
"quantity": 0.5,
}
]
// example filename (need to import moment.js to do below)
// like this => import moment from 'moment';
const csvDownloadDate = moment(new Date()).format('DD-MMM-YYYY'); // today
const filename = `${csvDownloadDate}-Services`;
// package up all data into object
const csvData = {
items,
headers,
filename,
}
// also works with no headers now
// const csvData = {
// items,
// filename,
// }
// call function from another file after importing CSVExport
CSVExport(csvData);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment