How to export dataTable as Excel format?

16.3k views Asked by At

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

2

There are 2 answers

4
davidkonrad On BEST ANSWER

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/

0
Rahul Singh On

This is what i did and it worked for me. Let me know if it helps you.

<script src="/js/jquery-1.12.0.min.js"></script> 
<script src="/js/datatables/jquery.dataTables.min.js"></script>
<script src="/js/datatables/dataTables.bootstrap.min.js"></script>
<script src="/js/datatables/dataTables.buttons.min.js"></script>
<script src="/js/datatables/buttons.bootstrap.min.js"></script>
<script src="/js/datatables/jszip.min.js"></script>
<script src="/js/datatables/pdfmake.min.js"></script>
<script src="/js/datatables/vfs_fonts.js"></script>
<script src="/js/datatables/buttons.html5.min.js"></script>
<script src="/js/datatables/buttons.print.min.js"></script>
<script src="/js/datatables/buttons.colVis.min.js"></script>

var table = $('#example').DataTable({
                lengthChange: false,
                buttons: [ 'copy', 'excel', 'pdf', 'colvis' ]
            });
table.buttons().container().appendTo( '#example_wrapper .col-sm-6:eq(0)' );