Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export value with Linebreaks into single cell in Excel with jQuery Datatables 2016

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".

like image 468
mesqueeb Avatar asked Dec 07 '22 23:12

mesqueeb


1 Answers

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.

like image 122
mesqueeb Avatar answered Feb 15 '23 08:02

mesqueeb