Tuesday, February 13, 2018

DataTable FAQ - exporting to EXCEL for column with input and selected text (dropdown menu)





For column with selected text from dropdown with select tag:
    data = table
    .cell( {row: row, column: column} )
    .nodes()
    .to$()
    .find(':selected')
    .text();


For column with input  tag:   
                            data = table
                            .cell( {row: row, column: column} )
                            .nodes()
                            .to$()
                            .find('input')
                            .val();   

  

Example JS code is as following (assume 9th column (column==8) with select dropdown
and thrid column (column--2) with input):   
    var buttonCommon = {
        exportOptions: {
            format: {
                body: function(data,  row, column) {
                             if(column==8)
                            data = table
                            .cell( {row: row, column: column} )
                            .nodes()
                            .to$()
                            .find(':selected')
                            .text();
                             if(column==2)
                            data = table
                            .cell( {row: row, column: column} )
                            .nodes()
                            .to$()
                            .find('input')
                            .val();               
                            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: {
                              columns: ':visible'
                     },

                      customize: function(xlsx) {
                            var sheet = xlsx.xl.worksheets['sheet1.xml'];
                            $('row c[r^="A"]', sheet).attr( 's', '50' ); //<-- left aligned text for A column                                       
                            var col = $('col', sheet);
                            col.each(function () {
                                     $(this).attr('width', 20);
                            });
          
              }
            })
          ]
      }
    );

No comments:

Post a Comment