这里有一些代码展示了如何实现这一点:
假设以下起点:
以及 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了。