在使用数据表导出到Excel时尝试格式化数据时遇到了一些问题。我的一个列包含小数点,并在浏览器中以表格形式显示“确定”。当我将表导出到excel时,这会将该列中的数字四舍五入,我不想发生这种情况。例如,如表'220419.07109'所示,当导出'220419.0711'时,如果这只是一个字符串来保持全部数字,我更愿意。
function formatDataForExport(data, row, column, node) {
var string = data.toString();
return string;
}
function drawDatatable(JSONData) {
var dataSet = [];
table = $("#div").DataTable({
data: dataSet,
columns: columns(),
columnDefs: [{
"targets": columnTargets(showConcludedColumns),
"visible": false,
"searchable": false
}],
info: false,
searching: false,
paging: false,
ordering: false,
autoWidth: true,
responsive: true,
buttons: [{
extend: 'excel',
text: "Export to Excel",
exportOptions: {
columns: ":visible",
format: {
body: formatDataForExport
}
}
}]
});
}
答案 0 :(得分:0)
您可以使用以下解决方案。
// Get the max value of an attribute of elements' list
var getMaxValue = function(elements, attr) {
var values = elements.map(function(){
return this.getAttribute(attr) || -Infinity;
}).toArray();
return Math.max.apply(Math, values);
}
$('#example').DataTable( {
dom: 'Bfrtip',
columns: [
{ data: 'Number' },
],
buttons: [
{
extend: 'excelHtml5',
customize: function(xlsx) {
//Get the built-in styles
//refer buttons.html5.js "xl/styles.xml" for the XML structure
var styles = xlsx.xl['styles.xml'];
//Create a custom number format
//Get the available id for the custom number format
var numFmtId = getMaxValue($('numFmts numFmt', styles), 'numFmtId') + 1
//XML Node: Custom number format for the timestamp column
var nFmt = '<numFmt numFmtId="' + numFmtId + '" formatCode="0.######################"/>';
// Add new node
el = $('numFmts', styles);
el.append(nFmt).attr('count', parseInt(el.attr('count'))+1);
//Create our own style to use the custom number format above
//XML Node: Custom style for the timestamp column
var style = '<xf numFmtId="' + numFmtId + '" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>';
// Add new node
el = $('cellXfs', styles);
el.append(style).attr('count', parseInt(el.attr('count'))+1);
// Index of our new style
var styleIdx = $('xf', el).length - 1;
//Apply new style to the first (A) column
var sheet = xlsx.xl.worksheets['sheet1.xml'];
//Set new style default for the column (optional)
$('col:eq(0)', sheet).attr('style', styleIdx);
//Apply new style to the existing rows of the first column ('A'), skipping header row
$('row:gt(0) c[r^="A"]', sheet).attr('s', styleIdx);
},
},
]
} );
工作JSFiddle
您可以在其中使用不同类型的格式:
简化版本,生成的文件可以在Excel中正确打开,但是快捷方式可能会影响其他XLSX文件读取软件:JSFiddle