Skip to content

Instantly share code, notes, and snippets.

@punit5658
Created August 21, 2017 12:21
Show Gist options
  • Save punit5658/724f1359fcaffc69d35193710ac8e38e to your computer and use it in GitHub Desktop.
Save punit5658/724f1359fcaffc69d35193710ac8e38e to your computer and use it in GitHub Desktop.
Export CSV using jQuery.
jQuery(document).ready(function($) {
var newarr = [];
$table = jQuery('table');
var dyarr = [];
$table.find('tr').each(function(){
$(this).find('td font').each(function(){
dyarr.push( $(this).html() ); // Column
});
newarr.push(dyarr); // Row
dyarr = [];
});
// Loop through the data array and build the csv file to be downloaded
// Each column is seperated by ";" and new line "\n" for next row
var csvContent = '';
newarr.forEach(function(infoArray, index) {
dataString = infoArray.join(';');
csvContent += index < newarr.length ? dataString + '\n' : dataString;
});
// Content is the csv generated string above
var download = function(content, fileName, mimeType) {
var a = document.createElement('a');
mimeType = mimeType || 'application/octet-stream';
if (navigator.msSaveBlob) { // IE10
navigator.msSaveBlob(new Blob([content], {
type: mimeType
}), fileName);
} else if (URL && 'download' in a) { //html5 A[download]
a.href = URL.createObjectURL(new Blob([content], {
type: mimeType
}));
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
}
}
download(csvContent, 'dowload.csv', 'text/csv;encoding:utf-8');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment