jQuery DataTable plugin-Change the headers while exporting as excel
— jQuery, DataTable, Quick Tip — 1 min read
Exporting as excel in a DataTable configured table is pretty straight forward. But what if we want to change the header while exporting as excel so that the web view has a different header and the excel has a different one.
But why would anyone need to do that?
The Problem...
Well lets take the example from this previous post where the table has a <select>
filter in the header instead of a column name.
Exporting this datatable as an excel file will generate something like this:
As you can see, the options in the filter dropdown become the header text in the excel.
The Solution...
We definitely need a better column name as the header in the excel file so lets try to do that. To achieve this, we need to add the below code to the initialization object.
..."buttons": [{ "extend": 'excel', "exportOptions": { "format": { "header": function(content, index) { // Here 2 is the index of the column // whose header name we want to change(0 based) return index === 2 ? "Gender" : content; } } }}]...
Here is a jsfiddle with a full working example.
After adding the above code, we get the desired header text in the column.