Skip to content

Instantly share code, notes, and snippets.

@Bellfalasch
Last active August 29, 2015 14:06
Show Gist options
  • Save Bellfalasch/81d6cf8676562baf74a7 to your computer and use it in GitHub Desktop.
Save Bellfalasch/81d6cf8676562baf74a7 to your computer and use it in GitHub Desktop.
Take an entire DataTable object and create a CSV output from it, skipping filtered rows, but showing all the columns (except the ones you select specifically in the code to not show).
// Setup: Just send your DataTables object (oTable) into this function onclick on some button.
// Inspired by this source, but more or less completely re-written because we need to respect filters on tables
// http://datatables.net/forums/discussion/11984/simple-csv-export-with-jquery-php
function table2csv(oTable) {
var csv = '';
var text;
var headers = [];
var columns = [];
var rows = [];
var skip = [2,12,14]; // Columns we do not want to include (used for search, filtering and sorting)
var separator = ";";
// Get header names
var tr = oTable.dataTableSettings[0].aoColumns;
$.each(tr, function(i,v) {
// Skip certain column headers we just use for search, filtering and sorting
if ( $.inArray(i,skip) == -1 ) {
var th = v.sTitle;
// Remove select-blocks entirely from header, we don't want it in the export - but use it's first child as the heading
if ( th.indexOf("select") !== -1 ) {
text = $( th ).find("option:first-child").text();
} else {
text = th;
}
// The finaliced header put inside quotes for Excel importing (but not really needed)
var header = '"' + text.replace(":","") + '"';
// actually datatables seems to copy my original headers so there is an amount of TH cells which are empty
if (text != "") {
headers.push(header);
}
}
});
// Add all the header columns to the main CSV-code/text block (will use that more later)
csv += headers.join(separator) + "\n\n";
// Fetch only visible rows (respect active filters)
var all_rows = oTable._('tr', {"filter":"applied"});
$.each( all_rows, function(index,elem) {
// For each row, find each column
$.each( elem, function(i,e) {
// Skip certain column headers we just use for search, filtering and sorting
if ( $.inArray(i,skip) == -1 ) {
// Our popup messes up the result, since it's the only one containing a div treat it differently
if ( e.indexOf("div") !== -1 ) {
text = $( e ).find("a:first-child").text();
} else {
text = e.replace(/<br>/g,", "); // Linebreaks needs to be replaced by commas
// All the other fields just need to get stripped from tags and whitespaces
text = strip_tags(text);
text = text.trim();
text = text.replace(/\n/g,"");
text = text.replace(/\r/g,"");
text = text.replace(/\t/g,"");
text = text.replace(/,$/, ""); // Remove trailing commas
}
// Switch semicolons to normal colons so our CSV doesn't get ruined by user content
text = text.replace(new RegExp(separator,"g"), "");
columns.push( text );
}
});
// Join the columns from this row into our row array, then empty the column array so we can go onto next table row
rows.push( columns.join(separator) );
columns = [];
});
// Add all the rows to the main CSV-code/text block
csv += rows.join("\n");
// Kill the CSV-div (for showing) if it exists
if($('.csv-data').length) $('.csv-data').remove();
// Create the div and show the CSV output
$('body').append('<div class="csv-data" style="width:100%;height:100%;background-color:hsla(1,0%,0%,0.6);position:absolute;top:0;z-index:1;"><form style="margin:10em auto;width:75%;height:75%;background-color:white;"><textarea style="width:100%;height:100%;" name="csv">'+csv+'</textarea></form></div>');
}
function strip_tags(html) {
var tmp = document.createElement("div");
tmp.innerHTML = html;
return tmp.textContent||tmp.innerText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment