Jquery DataTable 导出到 Excel 时的对齐和格式问题

问题描述 投票:0回答:1

在下面的示例中,我有一个 jquery 数据表并将其导出到 Excel 中。

 //myjsfile.js

function DisplayingData() {

  $('#mytable').DataTable({
   
    columnDefs: [{ type: 'currency', targets: [1] }, { targets: 1, className: "text-right" }],
    dom: 'lBfrtip',
    buttons: [
        {
            extend: 'excel',
            text: '<i class="fa fa-file-excel"></i> Excel',
            title: 'Balance',
            
            className: 'btn btn-success',
            exportOptions: {
                columns: ':not(.notexport)'
            }

        },
        
    ]   
});

// mypage.cshtml

<div id="mytable">
<table>
<thead>
            <tr>
                <th>
                    Balance
                </th>
             </tr>
    </thead>
<tbody>

  for (int i = 0; i < Model.CurrencyData.Count; i++)
   {
    @String.Format("{0:c}", Model.CurrencyData[i].Balance)

  }
</tbody>
</table>
</div>

下图是上面代码的示例,我在这里编写的与我的相同 原始代码。

////After adding customization, highlighted by //*****
 function DisplayingData() {

  $('#mytable').DataTable({
   
    columnDefs: [{ type: 'currency', targets: [1] }, { targets: 1, className: "text-right" }],
    dom: 'lBfrtip',
    buttons: [
        {
            extend: 'excel',
            text: '<i class="fa fa-file-excel"></i> Excel',
            title: 'Balance',
             //*****
            customize: function (xlsx) {
            var sheet = xlsx.xl.worksheets['sheet1.xml'];
                 $('row c[r ^= "A"]', sheet).attr('s', '52');//right align*/
            //*****
            className: 'btn btn-success',
            exportOptions: {
                columns: ':not(.notexport)'
            }

        },
        
    ]   
});

输出如下:

如何在导出到Excel时使该列右对齐而不丢失货币格式?

javascript jquery asp.net-mvc datatables
1个回答
0
投票

所以我除了找到任何捷径或简单的方法来解决这个问题 迭代每一行/单元格。下面的代码解决了我的问题。

      $('row c[r^="I"],c[r^="J"]', sheet).each(function () {
                    var cValue = $('is t', this).text(); 
                    if (cValue.length > 0) {
                       
                            $(this).attr('s', '57'); - first apply currency formatting
                            $(this).attr('s', '52'); - then set for right alignment
                    }
                });
© www.soinside.com 2019 - 2024. All rights reserved.