How to export dataTable as Excel format?

Balakumar B picture Balakumar B · Jun 22, 2016 · Viewed 13.6k times · Source

i have used tableTools plugins for Export datatable data, i have included following plugins

<script src="js/jquery-1.12.3.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/moment/moment.min.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.js" type="text/javascript"></script>
<script src="js/dataTables.tableTools.js"></script>

HTML code

<table id="result_table" class="display table table-bordered" cellspacing="0" width="100%"></table>

and my Initialization part,

var oTable = $('#result_table').dataTable({
            //"iDisplayLength": 50,
            //"order" : [[0,"desc"]],
            "columnDefs": [
                { "width": "16%", "targets": 1 }
              ],
            "lengthMenu": [[10, 50, 100, -1], [10, 50, 100, "All"]],
            "dom": 'T<"clear">lfrtip',
            "tableTools": {
                "sSwfPath": "copy_csv_xls_pdf.swf"
            }
        });

my actuall result is enter image description here

if i click Excel button my save as window isenter image description here

it was saved CSV file not as Xls or Xlsx format and also CSV button and Excel Button both are Export CSV file format only.. this is the problem i need to Export Excel format.. pls share your suggestion or solution

Answer

davidkonrad picture davidkonrad · Jun 22, 2016

Use this approach

oTableTools: {
  sSwfPath: "copy_csv_xls_pdf.swf",
  aButtons: [
    { sExtends: "xls",
      mColumns: 'visible',
      sFileName: 'export.xls',
      sToolTip: 'Save current table as XLS'
    }
  ]
}

The important things is sExtends: "xls" and sFileName to ensure a proper filename attached to the downloaded file.

But as other people mention in comments, you should really consider using the buttons plugin, here is a demo using that -> https://jsfiddle.net/zm825k01/