Skip to content

Instantly share code, notes, and snippets.

@mikeulkeul
Last active November 30, 2015 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeulkeul/e3d65ad5e08370d6f851 to your computer and use it in GitHub Desktop.
Save mikeulkeul/e3d65ad5e08370d6f851 to your computer and use it in GitHub Desktop.
Convert an HTML table to a CSV file that is download directly by the client
function createCSV(selector){
var contentString = "",
$row = document.querySelectorAll(selector),
$els, i,j, l,m, tmp;
for(i=0, l=$row.length; i<l; i++){
$els = $row[i].children;
tmp = [];
for(j=0, m=$els.length; j<m; j++){
tmp.push($els[j].innerText);
}
contentString += tmp.join(",")+"\n";
}
return contentString;
}
function download(data, opt){
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([data], {type: opt.mimeType}));
a.download = opt.filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
download(createCSV("table tr"), {
mimeType:'text/csv',
filename: 'table.csv'
})
@mikeulkeul
Copy link
Author

simple code to convert an html table to a csv file that is download directly by the client

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