Felix Cen
Felix Cen

Reputation: 763

JQuery Datatable export to excel corrupted when a cell has 2 or more links

I have a JQuery datatable with bootstrap style. I started adding the feature for exporting to excel using the button extensions, I am using the Html5 button extensions. I ran into a problem that the excel file is corrupted because my table has a column that has a comma separated list of link like below:

<tr>
     <td>A text column</td> 
     <td>
      <a class="modal-link" 
      data-modal-title="Title 1" 
      data-modal-url="/link1" 
      href="/link1" 
      title="Title 1">Link 1</a>, 
      <a class="modal-link" 
      data-modal-title="Title 2" 
      data-modal-url="/link2" 
      href="/link2" 
      title="Title 2">Link 2</a>
    </td>  
    ...
</tr>

Did anyone have this problem before?

Does anyone know how I could write a function to strip out the html for a cell in datatable/html5 button?

Thanks,

Upvotes: 0

Views: 2089

Answers (1)

Felix Cen
Felix Cen

Reputation: 763

Using exportOptions -> format -> body. Check if the data is html, if so, return text otherwise the data fixes the issue.

$.extend(true, $.fn.dataTable.defaults, {
    aLengthMenu: [[25, 50, 100, -1], [25, 50, 100, "All"]], // Setup number of entries per page
    iDisplayLength: 25, // Setup default number of entries per page,
    buttons: [
                {
                    extend: 'excelHtml5',
                    title: 'Excel Export',
                    extension: '.xlsx',
                    text: 'Export to Excel',
                     exportOptions: {
                        format: {
                            body: function ( data, column, row ) {                              
                                //if it is html, return the text of the html instead of html
                                if (/<\/?[^>]*>/.test(data)) {                                    
                                    return $(data).text();
                                } else {
                                    return data;
                                }                                                                
                            }
                        }
                    }
                }
    ],
    dom: 'Bfrtip'
});

Upvotes: 1

Related Questions