datatable.net preserve line breaks in exported documents

2

I am using the plugin: datatables.net

I have tried to preserve the line breaks
when exporting to excel, PDF or Print but it does not work for me:

stripNewlines: false

Update Script

Script:

$('.DataTable3').DataTable( {
    "autoWidth": true,
    "dom": '<"html5buttons"B>rt<"bottom"lfp><"clear">',
    "language": {
        "decimal":      ".",
        "emptyTable":       "No hay datos disponibles en la tabla",
        "info":         "Mostrando _START_ a _END_ de _TOTAL_ Registros",
        "infoEmpty":        "Mostrando 0 a 0 de 0 Registros",
        "infoFiltered":     "(Filtrado a Partir de _MAX_ Registros)",
        "infoPostFix":      "",
        "thousands":        ",",
        "lengthMenu":       "_MENU_",
        "loadingRecords":   "Cargando...",
        "processing":       "Procesando...",
        "search":       "",
        "searchPlaceholder": "Inserte su Busqueda",
        "searchPlaceholder": "Inserte su Busqueda",
        "zeroRecords":      "No Encontrado - lo siento",
        "paginate": {
            "first":        "Inicio",
            "last":         "Ultimo",
            "next":         "Siguiente",
            "previous":     "Anterior"
        },
        "aria": {
            "sortAscending":  ": activar para ordenar la columna ascendente",
            "sortDescending": ": activar para ordenar la columna descendente"
        }
    },
    "iDisplayLength": 10,
    "lengthMenu": [[5,10, 25, 50, 100, 250, 500, 1000, -1], [5,10, 25, 50, 100, 250, 500, 1000, "All"]],
    buttons: [{
        extend: 'collection',
        text: 'Herramientas',
        buttons: [
            {extend: 'copy', text: 'Copiar',
                exportOptions: {
                    columns: ':visible',
                    stripNewlines: false,
                    format: {
                        body: function(data){
                            //Antes de mandarse al PDF cada valor pasa por aqui y es evaluado
                            var valor ='';
                            if (~data.indexOf("<span")){
                                var datos = $(data);
                                datos.find("span").each(function(index) {
                                    var text = $(this).text();//get span content
                                    $(this).replaceWith(text);//replace all span with just content
                                });
                                data=datos.text();
                            }
                            if (~data.indexOf("<button")){
                                data='Correcto';
                            }
                            valor = data.toString(); //El campo debe ser STRING para que funcione
                            valor = valor.replace("<br>","\n");  //Aqui es donde le digo al JavaScript que reemplace <br/> el salto de linea HTML por el salto de linea \n
                        return valor;
                        }
                    }
                },
            },
            {extend: 'excel', title: 'ArchivoExcel', text: 'Excel',
                exportOptions: {
                    columns: ':visible',
                    stripNewlines: false,
                    format: {
                        body: function(data){
                            //Antes de mandarse al PDF cada valor pasa por aqui y es evaluado
                            var valor ='';
                            if (~data.indexOf("<span")){
                                var datos = $(data);
                                datos.find("span").each(function(index) {
                                    var text = $(this).text();//get span content
                                    $(this).replaceWith(text);//replace all span with just content
                                });
                                data=datos.text();
                            }
                            if (~data.indexOf("<button")){
                                data='Correcto';
                            }
                            valor = data.toString(); //El campo debe ser STRING para que funcione
                            valor = valor.replace("<br>","\n");  //Aqui es donde le digo al JavaScript que reemplace <br/> el salto de linea HTML por el salto de linea \n
                        return valor;
                        }
                    }
                },
            },
            {extend: 'pdfHtml5', title: 'ArchivoPDF', text: 'PDF',
                orientation: 'landscape',
                pageSize: 'LEGAL',
                exportOptions: {
                    columns: ':visible',
                    stripNewlines: false,
                    format: {
                        body: function(data){
                            //Antes de mandarse al PDF cada valor pasa por aqui y es evaluado
                            var valor ='';
                            if (~data.indexOf("<span")){
                                var datos = $(data);
                                datos.find("span").each(function(index) {
                                    var text = $(this).text();//get span content
                                    $(this).replaceWith(text);//replace all span with just content
                                });
                                data=datos.text();
                            }
                            if (~data.indexOf("<button")){
                                data='Correcto';
                            }
                            valor = data.toString(); //El campo debe ser STRING para que funcione
                            valor = valor.replace("<br>","\n");  //Aqui es donde le digo al JavaScript que reemplace <br/> el salto de linea HTML por el salto de linea \n
                        return valor;
                        }
                    }
                },
            },
            {extend: 'print', text: 'Imprimir',
                customize: function (win){
                    $(win.document.body).addClass('white-bg');
                    $(win.document.body).css('font-size', '10px');
                    $(win.document.body).find('table')
                    .addClass('compact')
                    .css('font-size', 'inherit');
                },
                exportOptions: {
                    columns: ':visible',
                    stripNewlines: false,
                    format: {
                        body: function(data){
                            //Antes de mandarse al PDF cada valor pasa por aqui y es evaluado
                            var valor ='';
                            if (~data.indexOf("<span")){
                                var datos = $(data);
                                datos.find("span").each(function(index) {
                                    var text = $(this).text();//get span content
                                    $(this).replaceWith(text);//replace all span with just content
                                });
                                data=datos.text();
                            }
                            if (~data.indexOf("<button")){
                                data='Correcto';
                            }
                            valor = data.toString(); //El campo debe ser STRING para que funcione
                            valor = valor.replace("<br>","\n");  //Aqui es donde le digo al JavaScript que reemplace <br/> el salto de linea HTML por el salto de linea \n
                        return valor;
                        }
                    }
                },
            },
        ]},
        {extend: 'colvis', text: 'Adm',},
        {
            text: 'Ayuda',
            action: function ( e, dt, node, config ) {
                $.jAlert({
                    'title': 'Ayuda de Herramientas',
                    'content': msgtext,
                    'theme': 'blue',
                    'size': 'lg',
                    'showAnimation': 'fadeInUp',
                    'hideAnimation': 'fadeOutDown'
                });
            }
        },
    ],
    "initComplete": function (oSettings) {
        var oTable = this;
        oTable.fnPageChange('last');
    },
    "order": [],
});

In Excel the data is seen in a single line without the jumps like the PDF. When I print the data value of each td in the console I get the following:

<span class="text-danger">CONT-Pen. Valoracion</span>,<br><span class="text-danger">CONT-Pen. Valoracion</span>

By means of the Script I have managed to eliminate the tags converted to / n, they do not work for me, neither in excel nor in PDF.

HTML:

<table class="table table-striped table-bordered table-hover DataTable3">
    <thead>
        <tr>
            <th>ORT</th>
            <th>ORS</th>
            <th>Marca</th>
            <th>Estado ORT</th>
            <th>Fecha Pedido</th>
            <th>Info</th>
            <th>TRI</th>
            <th>Estado TRI</th>
            <th>Cont</th>
            <th>Estado CONT</th>
            <th>ETA Contedor</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>ORT0000061</td><td>ORS0000063</td>
            <td>Aviko</td><td>ORT-Cerrado</td>
            <td> FP 2018-Ene-08</td>
            <td><button type="button" class="btn btn-xs btn-info" data-toggle="modal" data-target="#modal-info-DET-DOC-FCI-ORT0000061">Info</button></td>
            <td>TRI0000013 (Consol.)</td>
            <td>TRI-Gestion</td>
            <td><span class="text-danger">CONT0000024</span>,<br><span class="text-danger">CONT0000025</span>,<br><span class="text-danger">CONT0000026</span></td>
            <td><span class="text-danger">CONT-Pen. Valoracion</span>,<br><span class="text-danger">CONT-Pen. Valoracion</span>,<br><span class="text-danger">CONT-Pen. Valoracion</span></td>
            <td><span class="text-danger">ETA 2017-Dic-14</span>,<br><span class="text-danger">ETA 2017-Dic-14</span>,<br><span class="text-danger">ETA 2017-Dic-14</span></td>
        </tr>
    </tbody>
</table>

Libraries:

/*
 * This combined file was created by the DataTables downloader builder:
 *   https://datatables.net/download
 *
 * To rebuild or modify this file with the latest versions of the included
 * software please visit:
 *   https://datatables.net/download/#bs/jszip-3.1.3/pdfmake-0.1.27/dt-1.10.15/b-1.3.1/b-colvis-1.3.1/b-html5-1.3.1/b-print-1.3.1/fc-3.2.2/r-2.1.1
 *
 * Included libraries:
 *   JSZip 3.1.3, pdfmake 0.1.27, DataTables 1.10.15, Buttons 1.3.1, Column visibility 1.3.1, HTML5 export 1.3.1, Print view 1.3.1, FixedColumns 3.2.2, Responsive 2.1.1
 */

/*!
    
asked by Francisco Núñez 10.01.2018 в 16:54
source

1 answer

2

I leave you a part of the solution. In your code in the part you wanted to replace the "br" you were actually getting "," so replace all the commas with a regexp by "\ n"

valor = valor.replace(/\,/g,"\n");

With which you manage to make the "enters" inside the cell. Now the downside is that when abris the excel seems to be all on the same line, but if you double click on the field and update the height of the line, there are effectively "enters".

I would like to see how at the moment of the export set the height to each line, but I'm leaving and I can not continue to help!

I hope this helps find the answer to the problem.

EDIT

Added part of the @ FranciscoNúñez solution

It also changed the value replace to keep the commas to

valor = valor.replace(/\,/g,",\n");

Functional example below:

$('.DataTable3').DataTable( {
    "autoWidth": true,
    "dom": '<"html5buttons"B>rt<"bottom"lfp><"clear">',
    "language": {
        "decimal":      ".",
        "emptyTable":       "No hay datos disponibles en la tabla",
        "info":         "Mostrando _START_ a _END_ de _TOTAL_ Registros",
        "infoEmpty":        "Mostrando 0 a 0 de 0 Registros",
        "infoFiltered":     "(Filtrado a Partir de _MAX_ Registros)",
        "infoPostFix":      "",
        "thousands":        ",",
        "lengthMenu":       "_MENU_",
        "loadingRecords":   "Cargando...",
        "processing":       "Procesando...",
        "search":       "",
        "searchPlaceholder": "Inserte su Busqueda",
        "searchPlaceholder": "Inserte su Busqueda",
        "zeroRecords":      "No Encontrado - lo siento",
        "paginate": {
            "first":        "Inicio",
            "last":         "Ultimo",
            "next":         "Siguiente",
            "previous":     "Anterior"
        },
        "aria": {
            "sortAscending":  ": activar para ordenar la columna ascendente",
            "sortDescending": ": activar para ordenar la columna descendente"
        }
    },
    "iDisplayLength": 10,
    "lengthMenu": [[5,10, 25, 50, 100, 250, 500, 1000, -1], [5,10, 25, 50, 100, 250, 500, 1000, "All"]],
    buttons: [{
        extend: 'collection',
        text: 'Herramientas',
        buttons: [
            {
            	extend: 'excel', title: 'ArchivoExcel', text: 'Excel',
                exportOptions: {
                    columns: ':visible',
                    stripNewlines: false,
                    format: {
                        body: function(data){
                             var valor ='';
                            if (~data.indexOf("<span")){
                                var datos = $(data);
                                datos.find("span").each(function(index) {
                                    var text = $(this).text();//get span content
                                    $(this).replaceWith(text);//replace all span with just content
                                });
                                data=datos.text();
                            }
                     
                            if (~data.indexOf("<button")){
                                data='Correcto';
                            }
                            valor = data.toString(); //El campo debe ser STRING para que funcione
                            valor = valor.replace(/\,/g,",\n");  //aca te llegan , y no <br> asi que reemplazo eso.
           
                        return valor;
                        }
                    },
                },
                customize: function(xlsx) { 
					var styles = $('cellXfs', xlsx.xl['styles.xml']); 
					styles.append('<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1">'+'<alignment vertical="top" wrapText="1" />'+'</xf>'); 
					var sheet = xlsx.xl.worksheets['sheet1.xml']; 
					var col = $('c', sheet); col.each(function () {
						$(this).attr( 's', '55'); 
					}); 
					$('row:first c', sheet).attr( 's', '32' ); 
				}
            },
   
        ]},
        {extend: 'colvis', text: 'Adm',},
        {
            text: 'Ayuda',
            action: function ( e, dt, node, config ) {
                $.jAlert({
                    'title': 'Ayuda de Herramientas',
                    'content': msgtext,
                    'theme': 'blue',
                    'size': 'lg',
                    'showAnimation': 'fadeInUp',
                    'hideAnimation': 'fadeOutDown'
                });
            }
        },
    ],
    "initComplete": function (oSettings) {
        var oTable = this;
        oTable.fnPageChange('last');
    },
    "order": [],
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedcolumns/3.2.4/css/fixedColumns.dataTables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.1/css/responsive.dataTables.min.css"/>
 
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.colVis.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.print.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/fixedcolumns/3.2.4/js/dataTables.fixedColumns.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.1/js/dataTables.responsive.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
<table class="table table-striped table-bordered table-hover DataTable3">
    <thead>
        <tr>
            <th>ORT</th>
            <th>ORS</th>
            <th>Marca</th>
            <th>Estado ORT</th>
            <th>Fecha Pedido</th>
            <th>Info</th>
            <th>TRI</th>
            <th>Estado TRI</th>
            <th>Cont</th>
            <th>Estado CONT</th>
            <th>ETA Contedor</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>ORT0000061</td><td>ORS0000063</td>
            <td>Aviko</td><td>ORT-Cerrado</td>
            <td> FP 2018-Ene-08</td>
            <td><button type="button" class="btn btn-xs btn-info" data-toggle="modal" data-target="#modal-info-DET-DOC-FCI-ORT0000061">Info</button></td>
            <td>TRI0000013 (Consol.)</td>
            <td>TRI-Gestion</td>
            <td><span class="text-danger">CONT0000024</span>,<br><span class="text-danger">CONT0000025</span>,<br><span class="text-danger">CONT0000026</span></td>
            <td><span class="text-danger">CONT-Pen. Valoracion</span>,<br><span class="text-danger">CONT-Pen. Valoracion</span>,<br><span class="text-danger">CONT-Pen. Valoracion</span></td>
            <td><span class="text-danger">ETA 2017-Dic-14</span>,<br><span class="text-danger">ETA 2017-Dic-14</span>,<br><span class="text-danger">ETA 2017-Dic-14</span></td>
        </tr>
    </tbody>
</table>
    
answered by 17.01.2018 / 21:02
source