I'm trying to retain linebreaks made with <br>
in an HTML table when exporting it to excel with DataTables.
I followed their guide to replace certain things with Regex here: DataTables find and replace during export.
I was able to replace things no problem. But I fail to replace the <br>
with newlines that make content in the same cell retain their linebreaks.
This is my JS:
$( document ).ready(function() {
var fixNewLine = {
exportOptions: {
format: {
body: function ( data, column, row ) {
// Strip $ from salary column to make it numeric
return column === 5 ?
// THIS WORKS: data.replace(/test/ig, "blablabla"):
data.replace( /<br\s*\/?>/ig, '"'+"\r\n"+'"' ) :
data;
}
}
}
};
$('#table2excel').DataTable({
dom: 'Bfrtip',
buttons:[
$.extend( true, {}, fixNewLine, {
extend: 'copyHtml5'
} ),
$.extend( true, {}, fixNewLine, {
extend: 'excelHtml5'
} ),
$.extend( true, {}, fixNewLine, {
extend: 'pdfHtml5'
} )
]
});
});
The problem lies in this line:
data.replace( /<br\s*\/?>/ig, '"'+"\r\n"+'"' ) :
It gets saved in excel with only a pair of " "
instead of the actual line break.
Note that this also doesn't work:
data.replace( /<br\s*\/?>/ig, "\r\n"):
Any advice?
There is a similar thread here: Export value with Linebreaks into single cell in Excel. jQuery Datatables But it's outdated as it's a year old and there have been updates to DataTables and "TableTools" has been replaced by "Buttons".
The correct answer is:
data.replace( /<br\s*\/?>/ig, "\n" ) :
However, you need to press the "wrap text" button when opening the excel. If someone knows a way to have it wrapped automatically, please let me know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With