我想在导出时更改生成的CSV文件中列的名称。现在,表格和CSV文件显示" Severity"我想把这个名字更改为" Severe"在CSV中。
有没有办法做到这一点?
现在,我的代码看起来像这样:
opentable = $("#open").dataTable({
dom: "Bfrtip",
"data": openData,
"columns": [{
data: "severity", render: function (data, type, row) {
if (type === 'export') {
return data;
} else {
return '';
}
}
}],
"paging": true,
"searching": true,
buttons : [{
extend: 'csv',
exportOptions: {
columns: [0,1,2,3,4,5,6,7,8,9,10], orthogonal: 'export'
}
}]
});
答案 0 :(得分:2)
根据csv option:
customize:可用于修改导出数据内容的函数。该函数采用两个参数,即按钮配置的数据和按钮的配置对象。函数返回的值是将用于导出的值。
如果您希望向导出的数据添加公司页眉或页脚,描述数据或任何其他信息,这将非常有用。
使用此选项,您可以为第一个导出的行更改列名称“Severity”为“Severe”:
customize: function (csv) {
var csvRows = csv.split('\n');
csvRows[0] = csvRows[0].replace('"Severity"', '"Severe"')
return csvRows.join('\n');
}
var openData = [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011\/04\/25",
"office": "Edinburgh",
"severity": "5421"
},
{
"name": "Donna Snider",
"position": "Customer Support",
"salary": "$112,000",
"start_date": "2011\/01\/25",
"office": "New York",
"severity": "4226"
}
];
var opentable = $("#open").dataTable({
dom: "Bfrtip",
"data": openData,
"columns": [
{data: 'name'},
{data: 'position'},
{data: 'office'},
{data: 'salary'},
{data: 'start_date'},
{
data: "severity",
render: function (data, type, row) {
if (type === 'export') {
return data;
} else {
return '';
}
}
}],
"paging": true,
"searching": true,
buttons: [{
extend: 'csv',
exportOptions: {
columns: [0, 1, 2, 3, 4, 5],
orthogonal: 'export'
},
filename: 'file',
fieldSeparator: ';',
customize: function (csv) {
var csvRows = csv.split('\n');
csvRows[0] = csvRows[0].replace('"Severity"', '"Severe"')
return csvRows.join('\n');
}
}]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.3.1/css/buttons.dataTables.min.css">
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>
<table id="open">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
<th>Start date</th>
<th>Severity</th>
</tr>
</thead>
</table>