Search code examples
htmlexceldatatablesexport

Remove 'div' and 'span' on exporting dataTables to excel


I am trying to export an HTML table using dataTables plugins. My table has div and span tags inside td tag. While exporting the table, it is exported div and span tags as value. I tried to export only the value using the code

{extend: 'excelHtml5',
filename: 'Students with Accounts',
exportOptions: { format: { body: function (data, row, column, node ) 
{ return column === 4 ? "\0" + data : data;
return column === 4 ? data.text() : data; } } }
},

Still, I get the result as Screenshot of the exported Excel

Is there any way to export only text of the cell? Like this

Desired result


Solution

  • I think you meant to use node.innerText instead of data.text(). See innerText - and innerText has to operate on the node not on the data.


    But more than that, why do you need that exportOptions option at all?

    The default behavior is to use stripHtml set to true - unless you interfere with that by doing what you try to do in your example code.


    The key thing to remember is this: When you use:

    body: function (data, row, column, node )
    

    The data parameter represents the entire contents inside the <td> tag - including any HTML. By using some variation of:

    return data
    

    in that function, you are overriding the stripHtml default processing - and you will get the HTML in your Excel file.

    From the DataTables documentation I already linked to:

    data = The cell's innerHTML
    row = Cell's row index
    column = Cell's column index
    node = The cell node (since Buttons 1.2.2)