JS - EXPORT CSV OR XLS
by Rodwyn Moreno
JavaScript
function download() {
const headers = {
SiteId: 'Site Id',
Name: 'Contact Name',
Address: 'Address',
City: 'City',
State: 'State',
Zip: 'Zip Code',
CreatedBy: 'Creator',
CreatedDt: 'CreatedDt',
RevisedDt: 'RevisedDt',
RevisedBy: 'RevisedBy'
};
const itemsNotFormatted = [
{
SiteId: "S10003366085",
Name: "BARRY ZAMER",
Address: "284 LOCUST ST # 1",
City: "FLORENCE",
State: "MA",
Zip: "01062-2036",
CreatedDt: "2007-04-11",
CreatedBy: "matthewmartin",
RevisedDt: "2008-05-30",
RevisedBy: "CSG_OWNE"
}
];
const itemsFormatted = [];
itemsNotFormatted.forEach((item) => {
const tempObject = {};
Object.keys(item).map(key => {
tempObject[key] = item[key].replace(/,/g, '');
});
itemsFormatted.push(tempObject);
});
const fileTitle = 'export-data';
const fileType = 'csv';
exportFile(headers, itemsFormatted, fileTitle, fileType);
}
function exportFile(headers, items, fileTitle, fileType) {
if (headers) {
items.unshift(headers);
}
const jsonObject = JSON.stringify(items);
const file = convertToFile(jsonObject);
const exportedFilenmae = `${fileTitle}.${fileType}` || `export.${fileType}`;
const blob = new Blob([file], { type: `text/${fileType};charset=utf-8;` });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
const 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", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link); */
}
}
}
function convertToFile(objArray) {
const array = typeof objArray != 'object' ?...