如何在jQuery数据表中导出多行标题?

ind*_*ndu 1 jquery datatables datatables-1.10

嗨我正在使用jQuery Datatables 1.10.我试图导出Datatable多个标题行但没有得到.但它只导出第二个标题行.我正在使用按钮

  buttons: [{
                extend: 'excel',
                header: true

            }, {
                extend: 'print',
                header: true
            }
            ],
Run Code Online (Sandbox Code Playgroud)

我的表结构如

                        <table id="example" style="color: black;" class="display compact cell-border" cellspacing="0">
                            <thead>

                                <tr>
                                    <th rowspan="2">Sl.No</th>
                                    <th rowspan="2">Zone</th>
                                    <th colspan="2">Allotted</th>
                                    <th colspan="2">Vacant</th>
                                    <th colspan="2">Amenities</th>
                                    <th colspan="2">Total</th>
                                </tr>

                                <tr>
                                    <th>No Of Plots</th>
                                    <th>Area</th>
                                    <th>No Of Plots</th>
                                    <th>Area</th>
                                    <th>No Of Plots</th>
                                     <th>Area</th>
                                    <th>No Of Plots</th>
                                    <th>Area</th>

                                </tr>
                            </thead>
                        </table>
Run Code Online (Sandbox Code Playgroud)

小智 12

DataTable论坛上提到的解决方案不适用于最新版本.我以适合我的方式调整了它.我在buttons.html5.js中添加了一个本地函数:

var _fnGetHeaders = function(dt) {
    var thRows = $(dt.header()[0]).children();
    var numRows = thRows.length;
    var matrix = [];

    // Iterate over each row of the header and add information to matrix.
    for ( var rowIdx = 0;  rowIdx < numRows;  rowIdx++ ) {
        var $row = $(thRows[rowIdx]);

        // Iterate over actual columns specified in this row.
        var $ths = $row.children("th");
        for ( var colIdx = 0;  colIdx < $ths.length;  colIdx++ )
        {
            var $th = $($ths.get(colIdx));
            var colspan = $th.attr("colspan") || 1;
            var rowspan = $th.attr("rowspan") || 1;
            var colCount = 0;

            // ----- add this cell's title to the matrix
            if (matrix[rowIdx] === undefined) {
                matrix[rowIdx] = [];  // create array for this row
            }
            // find 1st empty cell
            for ( var j = 0;  j < (matrix[rowIdx]).length;  j++, colCount++ ) {
                if ( matrix[rowIdx][j] === "PLACEHOLDER" ) {
                    break;
                }
            }
            var myColCount = colCount;
            matrix[rowIdx][colCount++] = $th.text();

            // ----- If title cell has colspan, add empty titles for extra cell width.
            for ( var j = 1;  j < colspan;  j++ ) {
                matrix[rowIdx][colCount++] = "";
            }

            // ----- If title cell has rowspan, add empty titles for extra cell height.
            for ( var i = 1;  i < rowspan;  i++ ) {
                var thisRow = rowIdx+i;
                if ( matrix[thisRow] === undefined ) {
                    matrix[thisRow] = [];
                }
                // First add placeholder text for any previous columns.                 
                for ( var j = (matrix[thisRow]).length;  j < myColCount;  j++ ) {
                    matrix[thisRow][j] = "PLACEHOLDER";
                }
                for ( var j = 0;  j < colspan;  j++ ) {  // and empty for my columns
                    matrix[thisRow][myColCount+j] = "";
                }
            }
        }
    }

    return matrix;
};
Run Code Online (Sandbox Code Playgroud)

然后我DataTable.ext.buttons.excelHtml5将同一文件中的代码更改为:

    if ( config.header ) {
                /* ----- BEGIN changed Code ----- */ 
                var headerMatrix = _fnGetHeaders(dt);
                for ( var rowIdx = 0;  rowIdx < headerMatrix.length;  rowIdx++ ) {
                    addRow( headerMatrix[rowIdx], rowPos );
                }
                /* ----- OLD Code that is replaced: ----- */    
                //addRow( data.header, rowPos );
                /* ----- END changed Code ----- */  
                $('row c', rels).attr( 's', '2' ); // bold
    }
Run Code Online (Sandbox Code Playgroud)

  • 您能否指定 DataTable.ext.buttons.excelHtml5 在哪里 (2认同)

小智 7

添加到 Ronnie 给出的解决方案中,因为我们大多数人都对这种方法的工作原理感到困惑,所以想详细了解一下。

  1. 要使 Excel 按钮正常工作,请添加buttons.html5.js, dataTables.buttons.min.js, jszip.min.js

  2. 对于多行标题表导出,buttons.html5.js在文档底部添加以下功能

    var _fnGetHeaders = function(dt) {
    var thRows = $(dt.header()[0]).children();
    var numRows = thRows.length;
    var matrix = [];
    
    // Iterate over each row of the header and add information to matrix.
    for ( var rowIdx = 0;  rowIdx < numRows;  rowIdx++ ) {
        var $row = $(thRows[rowIdx]);
    
        // Iterate over actual columns specified in this row.
        var $ths = $row.children("th");
        for ( var colIdx = 0;  colIdx < $ths.length;  colIdx++ )
        {
            var $th = $($ths.get(colIdx));
            var colspan = $th.attr("colspan") || 1;
            var rowspan = $th.attr("rowspan") || 1;
            var colCount = 0;
    
            // ----- add this cell's title to the matrix
            if (matrix[rowIdx] === undefined) {
                matrix[rowIdx] = [];  // create array for this row
            }
            // find 1st empty cell
            for ( var j = 0;  j < (matrix[rowIdx]).length;  j++, colCount++ ) {
                if ( matrix[rowIdx][j] === "PLACEHOLDER" ) {
                    break;
                }
            }
            var myColCount = colCount;
            matrix[rowIdx][colCount++] = $th.text();
    
            // ----- If title cell has colspan, add empty titles for extra cell width.
            for ( var j = 1;  j < colspan;  j++ ) {
                matrix[rowIdx][colCount++] = "";
            }
    
            // ----- If title cell has rowspan, add empty titles for extra cell height.
            for ( var i = 1;  i < rowspan;  i++ ) {
                var thisRow = rowIdx+i;
                if ( matrix[thisRow] === undefined ) {
                    matrix[thisRow] = [];
                }
                // First add placeholder text for any previous columns.                 
                for ( var j = (matrix[thisRow]).length;  j < myColCount;  j++ ) {
                    matrix[thisRow][j] = "PLACEHOLDER";
                }
                for ( var j = 0;  j < colspan;  j++ ) {  // and empty for my columns
                    matrix[thisRow][myColCount+j] = "";
                }
            }
        }
    }
    
    return matrix;
    };
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在同一个文件中查找DataTable.ext.buttons.excelHtml5并替换代码块

    if(config.header){
        /*Existing code*/
    }
    
    Run Code Online (Sandbox Code Playgroud)

    if (config.header) {
        /* ----- BEGIN changed Code ----- */
        var headerMatrix = _fnGetHeaders(dt);
        for (var rowIdx = 0; rowIdx < headerMatrix.length; rowIdx++) {
            addRow(headerMatrix[rowIdx], rowPos);
        }
        /* ----- OLD Code that is replaced: ----- */
        //addRow( data.header, rowPos );
        /* ----- END changed Code ----- */
        $('row c', rels).attr('s', '2'); // bold
    }
    
    Run Code Online (Sandbox Code Playgroud)

就是这样。您将能够导出多个标题行。

如果您想导出合并的单元格,那么添加到上面的代码会对您有所帮助。

将此添加到按钮自定义功能。

buttons: [
    {
        extend: 'excel',
        customize: function (xlsx) {
            //Apply styles, Center alignment of text and making it bold.
            var sSh = xlsx.xl['styles.xml'];
            var lastXfIndex = $('cellXfs xf', sSh).length - 1;

            var n1 = '<numFmt formatCode="##0.0000%" numFmtId="300"/>';
            var s2 = '<xf numFmtId="0" fontId="2" fillId="0" borderId="0" applyFont="1" applyFill="0" applyBorder="0" xfId="0" applyAlignment="1">' +
                    '<alignment horizontal="center"/></xf>';

            sSh.childNodes[0].childNodes[0].innerHTML += n1;
            sSh.childNodes[0].childNodes[5].innerHTML += s2;

            var greyBoldCentered = lastXfIndex + 1;

            //Merge cells as per the table's colspan
            var sheet = xlsx.xl.worksheets['sheet1.xml'];
            var dt = $('#tblReport').DataTable();
            var frColSpan = $(dt.table().header()).find('th:nth-child(1)').prop('colspan');
            var srColSpan = $(dt.table().header()).find('th:nth-child(2)').prop('colspan');
            var columnToStart = 2;

            var mergeCells = $('mergeCells', sheet);
            mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
                attr: {
                    ref: 'A1:' + toColumnName(frColSpan) + '1'
                }
            }));

            mergeCells.attr('count', mergeCells.attr('count') + 1);

            var columnToStart = 2;

            while (columnToStart <= frColSpan) {
                mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
                    attr: {
                        ref: toColumnName(columnToStart) + '2:' + toColumnName((columnToStart - 1) + srColSpan) + '2'
                    }
                }));
                columnToStart = columnToStart + srColSpan;
                mergeCells.attr('count', mergeCells.attr('count') + 1);
            }

            //Text alignment to center and apply bold
            $('row:nth-child(1) c:nth-child(1)', sheet).attr('s', greyBoldCentered);
            for (i = 0; i < frColSpan; i++) {
                $('row:nth-child(2) c:nth-child(' + i + ')', sheet).attr('s', greyBoldCentered);
            }

            function _createNode(doc, nodeName, opts) {
                var tempNode = doc.createElement(nodeName);
                if (opts) {
                    if (opts.attr) {
                        $(tempNode).attr(opts.attr);
                    }
                    if (opts.children) {
                        $.each(opts.children, function (key, value) {
                            tempNode.appendChild(value);
                        });
                    }
                    if (opts.text !== null && opts.text !== undefined) {
                        tempNode.appendChild(doc.createTextNode(opts.text));
                    }
                }
                return tempNode;
            }

            //Function to fetch the cell name
            function toColumnName(num) {
                for (var ret = '', a = 1, b = 26; (num -= a) >= 0; a = b, b *= 26) {
                    ret = String.fromCharCode(parseInt((num % b) / a) + 65) + ret;
                }
                return ret;
            }
        }
    }
]
Run Code Online (Sandbox Code Playgroud)


Kan*_*kar 5

@ronnie /sf/answers/2977508131/ 的回答正在工作。为了使其工作,从 jquery 数据表下载构建器https://datatables.net/download/index下载文件。

请不要使用示例页面中的文件。

  • @JohnHayes-Reed 我没有足够的声誉来对其他用户的回答发表评论。 (2认同)

小智 0

最好检查此数据表文档。在 URL 下方 找到导出多行标题