我想导出多个数据表到Excel和PDF上各自的按钮点击后,在自定义搜索栏搜索关键字。
我已经写了一个代码,这是搜索关键字后导出PDF工作正常,但aftet修改Excel生成我的关键字搜索停止工作。请帮助,我不知道我在哪里错过的东西。
添加我的代码:
//My Code
$(document).ready( function() {
var tables = document.querySelectorAll('.data-table');
var tableElements = [];
var tableArr = [];
var tableContent = [];
//Export to Excel
function getHeaderNames(table) {
// Gets header names.
//params:
// table: table ID.
//Returns:
// Array of column header names.
var header = $(table).DataTable().columns().header().toArray();
var names = [];
header.forEach(function(th) {
names.push($(th).attr('data-exportname'));
});
return names;
}
function buildCols(data) {
// Builds cols XML.
//To do: define widths for each column.
//Params:
// data: row data.
//Returns:
// String of XML formatted column widths.
var cols = '<cols>';
for (i=0; i<data.length; i++) {
colNum = i + 1;
cols += '<col min="' + colNum + '" max="' + colNum + '" width="20" customWidth="1"/>';
}
cols += '</cols>';
return cols;
}
function buildRow(data, rowNum, styleNum) {
// Builds row XML.
//Params:
// data: Row data.
// rowNum: Excel row number.
// styleNum: style number or empty string for no style.
//Returns:
// String of XML formatted row.
var style = styleNum ? ' s="' + styleNum + '"' : '';
var row = '<row r="' + rowNum + '">';
for (i=0; i<data.length; i++) {
colNum = (i + 10).toString(36).toUpperCase(); // Convert to alpha
var cr = colNum + rowNum;
row += '<c t="inlineStr" r="' + cr + '"' + style + '>' +
'<is>' +
'<t>' + data[i] + '</t>' +
'</is>' +
'</c>';
}
row += '</row>';
return row;
}
function getTableData(table, title) {
// Processes Datatable row data to build sheet.
//Params:
// table: table ID.
// title: Title displayed at top of SS or empty str for no title.
//Returns:
// String of XML formatted worksheet.
var header = getHeaderNames(table);
var table = $(table).DataTable();
var rowNum = 1;
var mergeCells = '';
var ws = '';
ws += buildCols(header);
ws += '<sheetData>';
if (title.length > 0) {
ws += buildRow([title], rowNum, 51);
rowNum++;
mergeCol = ((header.length - 1) + 10).toString(36).toUpperCase();
mergeCells = '<mergeCells count="1">'+
'<mergeCell ref="A1:' + mergeCol + '1"/>' +
'</mergeCells>';
}
ws += buildRow(header, rowNum, 2);
rowNum++;
// Loop through each row to append to sheet.
table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
var rowData = [];
//var data = this.data();
var rowNode = this.node();
$(rowNode).find("td:visible").each(function () {
var cellData = $(this).attr('data-exportname');
rowData.push(cellData);
});
// If data is object based, then it needs to be converted
// to an array before sending to buildRow()
ws += buildRow(rowData, rowNum, '');
rowNum++;
} );
ws += '</sheetData>' + mergeCells;
return ws;
}
function setSheetName(xlsx, name) {
// Changes tab title for sheet.
//Params:
// xlsx: xlxs worksheet object.
// name: name for sheet.
if (name.length > 0) {
var source = xlsx.xl['workbook.xml'].getElementsByTagName('sheet')[0];
source.setAttribute('name', name);
}
}
function addSheet(xlsx, table, title, name, sheetId) {
//Clones sheet from Sheet1 to build new sheet.
//Params:
// xlsx: xlsx object.
// table: table ID.
// title: Title for top row or blank if no title.
// name: Name of new sheet.
// sheetId: string containing sheetId for new sheet.
//Returns:
// Updated sheet object.
//Add sheet2 to [Content_Types].xml => <Types>
//============================================
var source = xlsx['[Content_Types].xml'].getElementsByTagName('Override')[1];
var clone = source.cloneNode(true);
clone.setAttribute('PartName','/xl/worksheets/sheet' + sheetId + '.xml');
xlsx['[Content_Types].xml'].getElementsByTagName('Types')[0].appendChild(clone);
//Add sheet relationship to xl/_rels/workbook.xml.rels => Relationships
//=====================================================================
var source = xlsx.xl._rels['workbook.xml.rels'].getElementsByTagName('Relationship')[0];
var clone = source.cloneNode(true);
clone.setAttribute('Id','rId'+sheetId+1);
clone.setAttribute('Target','worksheets/sheet' + sheetId + '.xml');
xlsx.xl._rels['workbook.xml.rels'].getElementsByTagName('Relationships')[0].appendChild(clone);
//Add second sheet to xl/workbook.xml => <workbook><sheets>
//=========================================================
var source = xlsx.xl['workbook.xml'].getElementsByTagName('sheet')[0];
var clone = source.cloneNode(true);
clone.setAttribute('name', name);
clone.setAttribute('sheetId', sheetId);
clone.setAttribute('r:id','rId'+sheetId+1);
xlsx.xl['workbook.xml'].getElementsByTagName('sheets')[0].appendChild(clone);
//Add sheet2.xml to xl/worksheets
//===============================
var newSheet = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" mc:Ignorable="x14ac">'+
getTableData(table, title) +
'</worksheet>';
xlsx.xl.worksheets['sheet' + sheetId + '.xml'] = $.parseXML(newSheet);
}
tableElements = tables.forEach( (element, index) => {
if(index != 0) {
return $(element).DataTable();
}
return $(element).DataTable({
dom: 'Bftrip',
buttons: [
{
extend: 'excelHtml5',
text: 'Excel',
exportOptions: {
orthogonal: "sort",
format: {
header: function (data, column, node){
if(node.dataset.exportname != undefined){
return node.dataset.exportname;
}
return data;
},
body: function (data, row, column, node) {
if(node.dataset.exportname != null){
return node.dataset.exportname;
}
return data;
}
}
},
customize: function( xlsx ) {
setSheetName(xlsx, 'Employees');
// process additional DataTables in the web page:
$('table').each(function( index ) {
if ( index > 0 ) {
var tableID = '#' + $( this ).attr('id');
var rowOneTitle = $( this ).attr('data-rowonetitle');
var sheetName = $( this ).attr('data-sheetname');
var sheetID = index + 1;
addSheet(xlsx, tableID, rowOneTitle, sheetName, sheetID);
}
});
}
}
]
});
});
//Export to PDF
$('#ExportPdf').click(function(){
var config = {
className:"buttons-pdf buttons-html5",
customize:null,
download:"download",
exportOptions:{
format: {
header: function (data, column, node){
if(node.dataset.exportname != null){
return node.dataset.exportname;
}
return data;
},
body: function (data, row, column, node) {
if(node.dataset.exportname != null){
return node.dataset.exportname;
}
return data;
}
}
},
extension:".pdf",
filename:"*",
header:true,
namespace:".dt-button-2",
orientation:"portrait",
pageSize:"A4",
title:"*"
};
tables.forEach((element, index) => {
var dataTable = $(element).DataTable();
var data = dataTable.buttons.exportData( config.exportOptions );
var info = dataTable.buttons.exportInfo( config );
var rows = [];
if (config.header) {
rows.push($.map(data.header, function (d) {
return {
text: typeof d === 'string' ? d : d+'',
style: 'tableHeader'
};
}));
}
for (var i=0, ien=data.body.length ; i<ien ; i++ ) {
rows.push($.map(data.body[i], function ( d ) {
return {
text: typeof d === 'string' ? d : d+'',
style: i % 2 ? 'tableBodyEven' : 'tableBodyOdd'
};
}));
}
tableContent.push(
{
text: tableArr[index]
}
);
tableContent.push({
table: {
headerRows: 1,
body: rows,
},
margin: [ 0, 2, 0, 20 ], // left, top, right, bottom
layout: "noBorders",
});
});
var doc = {
pageSize: config.pageSize,
pageOrientation: config.orientation,
content: tableContent,
styles: {
tableHeader: {
bold: true,
fontSize: 11,
color: 'white',
fillColor: '#2d4154',
alignment: 'center'
},
tableBodyEven: {},
tableBodyOdd: {
fillColor: '#f3f3f3'
},
tableFooter: {
bold: true,
fontSize: 11,
color: 'white',
fillColor: '#2d4154'
},
title: {
alignment: 'center',
fontSize: 15
},
message: {}
},
defaultStyle: {
fontSize: 10
}
};
if ( config.customize ) {
config.customize( doc, config );
}
pdfMake.createPdf(doc).download('Vehicle Status Report.pdf');
});
$('#mySearch').on( 'keyup click', function () {
tableElements.forEach(element => {
element.tables().search($(this).val()).draw();
});
});
$('.dataTables_filter').addClass('hide-elements');
});
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
.hide-elements{
display: none;
}
</style>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
<button id="ExportPdf" type="button">Export All</button>
Custom Search: <input type="search" id="mySearch">
<table class="data-table" data-sheetname="Table 1" data-rowonetitle="Table 1" id="table-1">
<thead>
<tr>
<th data-exportname="Company">Company1</th>
<th data-exportname="Contact">Contact1</th>
<th data-exportname="Country">Country1</th>
</tr>
</thead>
<tbody>
<tr>
<td data-exportname="Alfreds Futterkiste">Alfreds Futterkiste</td>
<td data-exportname="Maria Anders">Maria Anders</td>
<td data-exportname="Germany">Germany</td>
</tr>
<tr>
<td data-exportname="Centro comercial Moctezuma">Centro comercial Moctezuma</td>
<td data-exportname="Francisco Chang">Francisco Chang</td>
<td data-exportname="Mexico">Mexico</td>
</tr>
<tr>
<td data-exportname="Ernst Handel">Ernst Handel</td>
<td data-exportname="Roland Mendel">Roland Mendel</td>
<td data-exportname="Austria">Austria</td>
</tr>
</tbody>
</table>
<br>
<table class="data-table" data-sheetname="Table 2" data-rowonetitle="Table 2">
<thead>
<tr>
<th data-exportname="Company">Company</th>
<th data-exportname="Contact">Contact</th>
<th data-exportname="Country">Country</th>
</tr>
</thead>
<tbody>
<tr>
<td data-exportname="Alfreds Futterkiste">Alfreds Futterkiste</td>
<td data-exportname="Maria Anders">Maria Anders</td>
<td data-exportname="Germany">Germany</td>
</tr>
</tbody>
</table>
<br>
<table class="data-table" data-sheetname="Table 3" data-rowonetitle="Table 3">
<thead>
<tr>
<th data-exportname="Company">Company</th>
<th data-exportname="Contact">Contact</th>
<th data-exportname="Country">Country</th>
</tr>
</thead>
<tbody>
<tr>
<td data-exportname="Centro comercial Moctezuma">Centro comercial Moctezuma</td>
<td data-exportname="Francisco Chang">Francisco Chang</td>
<td data-exportname="Mexico">Mexico</td>
</tr>
<tr>
<td data-exportname="Ernst Handel">Ernst Handel</td>
<td data-exportname="Roland Mendel">Roland Mendel</td>
<td data-exportname="Austria">Austria</td>
</tr>
</tbody>
</table>
1条答案
按热度按时间vecaoik11#
我只是在我自己的代码中做了几行修改,得到了预期的输出。我已经将数据表对象推到了同一个tableElement数组中,我的自定义搜索开始工作得非常好,Excel文件生成也开始使用所需的输出。
将Data表对象推送到相同的tableElement Array中,因此我的自定义搜索开始工作