Remove Empty Rows from Excel Export Datatables
Remove Empty Rows from Excel Export Datatables
These day I was trying to Export Child Rows to the Excel and with the powerful of forum and amazing people here, I was able to do that with the sample provided here by @AndreNeves . The edited code:
function exportTableToCSV($table, filename, role) {
//To Get Header and Row
var $Tabla_Nueva = $table.find('tr:has(td,th)');
var Tabla_Nueva2= $Tabla_Nueva.filter(function() {
return (this.childElementCount != 1 );
});
var $rows = Tabla_Nueva2,
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
colDelim = (filename.indexOf("xls") !=-1)? '"\t"': '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function (i, row) {
var $row = $(row);;
if ($row.attr('class') == undefined) {
if (role == "Fin") {
var $cols = $row.find('td:not(.main),th:not(.main)');
//var $cols = $row.find(':not(.child)');
} else {
var $cols = $row.find('td:not(.child),th:not(.child)');
}
return $cols.map(function(j, col) {
var $col = $(col);
var text = $col.text().split('/');
return text; //.replace('"', '""'); // escape double quotes
}).get().join(tmpColDelim);
} else {
if (role == "Fin") {
var $cols = $row.find('td:not(.main),th:not(.main)');
//var $cols = $row.find(':not(.child)');
} else {
var $cols = $row.find('td:not(.child),th:not(.child)');
}
return $cols.map(function(j, col) {
var $col = $(col);
var text = $col.html().split('<br>');
for (var i = 0; i < text.length; i++) {
//To Replace Html Tag
text[i] = text[i].replace(/<(\/)?([a-zA-Z]*)(\s[a-zA-Z]*=[^>]*)?(\s)*(\/)?>/g, '');
}
return text;
}).get().join(tmpColDelim);
}
csv =csv +'"\r\n"' +'fin '+'"\r\n"';
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"';
download_csv(csv, filename);
}
The export of Child Rows was doing great and I have the output as below in the Excel file:
As you can see, there were some empty rows shown in the Excel file. The empty rows was because of me filtering out the content that I want it to be in Excel by using class name (see $row.find) at the above code. How can I remove the empty rows to make it as whole list? Any suggestion is appreciated.
Answers
This example only exports rows that have "London" as the office. You could tweak to that to test for empty/non-empty rows,
Colin
Thanks @colin . Another question, is there anyway I can format my header in exportOption with other html elements instead of the header that is default?
I mean what I want to achieve is to get the child row header as the export Excel header, is there anyway I can access to child row header in the exportOptions ?
You should be able to use
messageTop
for that - this thread discusses it which will hopefully get you going,Colin