Tuesday, February 13, 2018

DataTable FAQ - Keep line break when exporting to EXCEL, columns and rows visible





To keep line break <br/>, <br /> or <br> when exporting to EXCEL,
we can use data.replace(/<br\s*\/?>/ig, "\r\n") to replace
<br/>, <br /> or <br> to \r\n in EXCEL.
But the cell text should be wrapped.
    $('row c', sheet).each( function () {
                $(this).attr( 's', '55' );
    });   

Only export visible rows and columns to EXCEL
                                  extend: 'excel',
                                  exportOptions: {
                                          rows: ':visible',
                                          columns: ':visible'
                                 },

Example JS code is as following:   
    var buttonCommon = {
        exportOptions: {
            format: {
                body: function(data,  row, column) {
               
                            data = data.replace(/<br\s*\/?>/ig, "\r\n");//should be with wrapped text
                            return data;
                },
                header: function(data, column, row) {
                            data = data.replace(/<br\s*\/?>/ig, "\r\n");//should be with wrapped text
                            return data;
                }
              }
            }
    };
    $.extend(true, $.fn.dataTable.defaults, {
              "lengthChange": false,
              "pageLength": 100,
              "orderClasses": false,
              "stripeClasses": [],
               "destroy": true,
              dom: 'Bfrtip',
              buttons: [
                    $.extend(true, {}, buttonCommon, {
                      extend: 'excel',
                      exportOptions: {

                             rows: ':visible',    
                          columns: ':visible'
                     },

                      customize: function(xlsx) {
                            var sheet = xlsx.xl.worksheets['sheet1.xml'];
                      //All cell wrapped text
                            $('row c', sheet).each( function () {
                                        $(this).attr( 's', '55' );
                            });       
          
              }
            })
          ]
      }
    );

No comments:

Post a Comment