简体   繁体   中英

Datatables export to excel with data types

I have a table:

Name     Reg.number   Limit        Date
Jon      123455665    100 000.00   24.09.2018
Foo      123423423    55 000.00    23.09.2018

I am using datatables to create excel and it works fine but I need to specify data types in exported excel. Right now in excel all data is considered to be "Genereal" but I need it to recognize that:

Jon = text
Reg.number = text
Limit = Number (In perfect scenario with thousand separator and 2 digits after .)
Data = date

Here is my code so far:

<script>

$(document).ready(function() {
    $('#datatable').DataTable();

    $.fn.dataTable.moment( 'D.M.YYYY' );

    var table = $('#datatable-buttons').DataTable({
        lengthChange: false,
        buttons: ['excel'],
    });

    table
        .order( [4 , 'desc'] )
        .draw();

    table.buttons().container()
        .appendTo('#datatable-buttons_wrapper .col-md-6:eq(0)');
} );

So my current output is: Excel where all data are considered to be "general".

My desired output is: Excel where all columns are considered according to data type. Text, Number(decimal), date.

I really cant find an answer in datatables documentation. They have literally 1-2 examples that doesnt tell much so I would appreciate code examples rather that a link to documentation that I have been reading for past few hours.

As mentioned, I believe you need to convert the values into something recognizable. The problem is Excel (or other readers) which of course not is able to figure out that "55 000.00" should be considered as a number. As a human, I am not sure how to interpret this either :)

exportOptions: {
  format: {
     body: function(data, row, column, node) {
        switch (column) {
          case 2 :
            return data.replace(/ /, ',')
            break
          case 3 : 
            return moment(data, 'DD.MM.YYYY').format('MM/DD/YYYY')
            break
          default :
            return data
            break
        }
     }
  }    
}    

modify this to your needs. Have made a fiddle -> https://jsfiddle.net/sv42o8yw/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM