【问题标题】:How to add additional data from an array to export to excel in jquery data table如何从数组中添加其他数据以导出到 jquery 数据表中的 excel
【发布时间】:2020-08-23 04:01:05
【问题描述】:

我有以下列和数据的 jquery 数据表。

我正在使用内置功能将数据导出到 excel 中,它按预期工作。

 var table = $('#example').DataTable({
                dom: 'Bfrtip',
                buttons: [
                    'copyHtml5',
                    'excelHtml5',
                    'csvHtml5',
                    'pdfHtml5'
                ],
                stateSave: true,
                
                
               
                rowsGroup: [// Always the array (!) of the column-selectors in specified order to which rows grouping is applied
                    // (column-selector could be any of specified in https://datatables.net/reference/type/column-selector)

                    1, 0
                ]
               
            });

现在,我有一个数组,其数据类似于网格定义。

 var aData = new Array();
            var array1 = {

                Name: "David",
                Position: "Software Engineer",
                Office: "Tokyo",
                OfficeId: "1000",
                Age: 29,
                "Start date": "2011/04/25",
                Salary: "$320,800"
            };
            aData.push(array1);
            

要求是在单击excel按钮时将数组数据添加到excel中。 即,在导出时将来自外部数组的数据包含到网格值。这可能吗? excel should 如下。

任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: jquery excel datatable datatables export-to-excel


    【解决方案1】:

    这里有一些代码展示了如何实现这一点:

    假设以下起点:

    以及 JavaScript 数组变量中的以下“额外”数据行:

    var extraData = [
      "David",
      "Software Engineer 2",
      "Tokyo",
      25,
      "04/25/2011",
      320800
    ];
    

    然后当数据导出到 Excel 时,表格如下所示:

    数据表代码:

    <script type="text/javascript">
    
    $(document).ready(function() {
    
      var extraData = [
        "David",
        "Software Engineer",
        "Tokyo",
        29,
        "04/25/2011",
        320800
      ];
    
      var table = $('#example').dataTable({
        dom: 'Bfrtip',
        buttons: [
          {
            extend: 'excelHtml5',
            title: '', // no title row
            text: 'Excel',
            customize: function ( xlsx ){
              var sheet = xlsx.xl.worksheets['sheet1.xml'];
              insertRowAfter( 6, sheet );
              populateRow( 7, extraData, sheet );
            }
          }
        ]
    
      });
    
      // Insert a new row after the rowNum row. The new row is 
      // cloned from the rowNum row.
      function insertRowAfter(rowNum, sheet) {
        var $src_row = $( 'row[r=' + rowNum + ']', sheet );
        var newRowID = parseInt( $src_row.attr( 'r' ) ) + 1;
        var $new_row = $src_row.clone().attr( 'r', newRowID );
    
        // fix the cell references in the new row:
        $new_row.children( 'c' ).each(function( index ) {
          var newCellID = $( this ).attr( 'r' ).match(/[A-Z]+/) + newRowID
          $( this ).attr( 'r', newCellID );
        });
    
        // Increment the row and cell references in all rows below
        // where the new row will be inserted:
        $src_row.nextAll('row').each(function( index ) {
          var nextRowID = parseInt( $( this ).attr( 'r' )) + 1;
          $( this ).attr( 'r', nextRowID );
          $( this ).children( 'c' ).each(function( index ) {
            var nextCellID = $( this ).attr( 'r' ).match(/[A-Z]+/) + nextRowID
            $( this ).attr( 'r', nextCellID );
          });
    
        });
    
        // Insert the new row:
        $src_row.after($new_row);
      }
    
      function populateRow( row, data, sheet ) {
        // Assumes data starts in column A, with no gaps. Assumes 
        // no more than 26 columns (A through Z).
        data.forEach(function (item, index) {
          var col = String.fromCharCode(65 + index); // 65 = ascii 'A'
          if ( typeof item === 'string' ) {
            $('c[r=' + col + row + '] t', sheet).text( item );
          } else if ( typeof item === 'number' ) {
            $('c[r=' + col + row + '] > v', sheet).html( item );
          }
        });
      }
    
    });
    </script>
    

    注意事项:

    1) 我将“额外行”数据的 JS {...} 对象更改为数组 [...]。如果您愿意,可以更改代码并将其改回 - 但对于我的演示,我想保持简单。

    2) “额外行”数组中的数据必须以特定方式格式化 - 我的意思是:对于数字,确保数据在引号中。例如,美元金额采用任何逗号或美元符号进行格式化。让 Excel 为您进行格式化。

    3) 这段代码有些基础,而 Excel 工作表相当复杂。对于您问题中的特定场景,这是可行的。但很有可能需要调整代码以处理其他类型的数据 - 或空/空白值等。只是为了警告你。

    我想说,尽你所能避免像这样插入新行。或者使用可能更好地处理这个问题的库。

    编辑

    假设我们从对象 {...} 而不是数组 [...] 开始:

      var dataObject = {
        Name: "David",
        Position: "Software Engineer",
        Office: "Tokyo",
        Age: 29,
        "Start date": "2011/04/25",
        Salary: 320800
      };
    

    有多种方法可以处理这个问题。

    这是一种方法,我们在使用之前将数据转换为数组:

    var extraData = [];
    for(var o in dataObject) {
      extraData.push(dataObject[o]);
    }
    

    现在我们可以像上面一样使用extraData了。

    【讨论】:

    • 感谢您的回复,感谢您的帮助。我会试试这个。您能否帮助使用自定义数组/json 数据作为导出选项而不是网格数据。在 Jquerydata 表中这可能吗?
    • @andrewjames- 有没有办法用自定义中的新 json 对象替换 xlsx:函数( xlsx )。因此它将使用新提供的 json 对象创建 excel。如果我错了,请纠正我。客户改变了他们的要求,这就是为什么我也在检查新的替代方案。非常感谢您的宝贵帮助。
    • 您是说您想将数据导出到 Excel,使用 DataTables 的“excel”按钮,但您想忽略 DataTable 中的所有数据,而是使用不同的 JSON 数据集?如果这是正确的,那么 DataTables 是错误的技术。还是我误解了你的问题?
    • 是的,你是对的..这就是我要找的。​​span>
    • 导出过程中会添加一些额外的数据。我已经在自定义方法中进行了自定义行合并。所以考虑在自定义方法中添加新数据会有所帮助,以便可以使用所有编写的行合并代码。
    【解决方案2】:

    我有一个解决方案,我在这里分享。

    在导出数据的同时,我们可以利用下面的方法将自定义数据添加到jquery数据表中。

      customizeData: function (data) {
      
      }

    在这里,您将在“data.header”中获取标题,并且在“data.body”中将提供单元格数据。

    所以,我们可以在这里操作整个 excel 表头/单元格数据。

    我已经为单元格数据创建了自定义数组,并在“data.body”中替换如下

    customize: function (xlsx) {
    
    
                        },
    customizeData: function (data) {
                            
         var excelbodyData = getBodyArray();
        var excelHeader =getHeaderArray();
         data.header = [];
         data.header = excelHeader;
         data.body = [];
          data.body = excelbodyData;
      }

    【讨论】:

    • andrewjames ...请看答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多