我有一个使用DataTables和JQuery的报告,使用HTML5的导出功能。我有以下专栏
Code
| Initial date
| End Date
| Collection Status
| Amount to be paid
要从我的Excel中导出,我使用以下代码:
buttons : [
{
extend : 'excelHtml5',
exportOptions: {
columns: ':visible',
format: {
body: function(data, row, column, node) {
return data.replace(',', '.');
}
}
},
className : 'btn btn-primary pull-right',
text : 'Descargar <i class="glyphicon glyphicon-export"></i>',
customize : function(xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
$('row c', sheet).attr('s', '25');
$('row:first c', sheet).attr('s', '27');
}
},
....
]
我想得到最后所有值的总和,我该如何实现呢?
答案 0 :(得分:2)
您希望实施Footer callback。
并确保通过在按钮配置中添加footer: true
来包含要导出到Excel的页脚。
答案 1 :(得分:1)
您可以使用excelHtml5按钮类型的自定义方法在导出到文件之前更改样式和数据。
$(document).ready(function() {
$('#table').dataTable({
data: [{
name: "Tiger Nixon",
salary: "$3,120",
},
{
name: "Garrett Winters",
salary: "$5,300",
},
],
columns: [{
data: "name"
},
{
data: "salary"
}
],
dom: 'Bfrtip',
buttons: [{
extend: 'excelHtml5',
filename: 'datatable',
customize: function(xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'],
sum = 0;
// read each row
// Loop over the cells in column `B`
$('row c[r^="B"]', sheet).each(function() {
// Get the value and strip the non numeric characters
var value = $(this).text();
sum += Number(value.replace(/[^0-9\.-]+/g, ""));
});
// Create our number formatter.
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
// the default value for minimumFractionDigits depends on the currency
// and is usually already 2
minimumFractionDigits: 2,
});
function addTotal(index, data) {
msg = '<row r="' + index + '">';
for (i = 0; i < data.length; i++) {
var key = data[i].k;
var value = data[i].v;
msg += '<c t="inlineStr" r="' + 'B' + '4' + '" s="42">';
msg += '<is>';
msg += '<t>' + formatter.format(sum) + '</t>';
msg += '</is>';
msg += '</c>';
}
msg += '</row>';
return msg;
}
//insert
var r1 = addTotal(1, [{
k: 'A',
v: 'ColA'
}]);
sheet.childNodes[0].childNodes[1].innerHTML = r1 + sheet.childNodes[0].childNodes[1].innerHTML;
}
}]
});
});
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.js"></script>
<link href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script>
<body>
<div class="container">
<table id="table">
</table>
</div>
</body>