[英]Export table data to excel using jQuery
我正在使用此代碼:
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
這是我的提交按鈕:
<td><input type="button" onclick="tableToExcel('project_table', 'W3C Example Table')" value="Export to Excel"></td>
我遇到的問題是我的一些輸入是下拉菜單和輸入,但是在構建excel文件時它們是隱藏的。 因此,當excel文件首次生成時,您將看到所有數據,並在2秒內看到所有具有隱藏下拉菜單和輸入的數據變為空白並呈現html。
圖片1:
圖片2:
我正在嘗試使用textExtraction,但對我來說不起作用。
$('#project_table').tablesorter({
textExtraction: myTextExtraction
});
//todo: try getting the dataTable to work...
// it might be way better, just not sure how it would handle
// adding unrelated rows on the fly (comments)
//$('#project_table').dataTable();
var myTextExtraction = function(node)
{
var elem = $(node);
var theVal = null;
if (elem.hasClass('edit')) {
elem.children().each(function() {
if ($(this).css('display') != 'none') {
if ($(this).is('span')) {
theVal = $(this).text();
} else { //all other element types (input, select, etc)
theVal = $(this).val();
}
}
});
} else {
theVal = elem.text();
}
//console.log(theVal);
var c = node.childNodes.length;
if (c == 1) {
theVal = node.innerHTML.trim();
} else if (c == 5) {
theVal = node.childNodes[3].innerHTML.trim();
}
//console.log(theVal);
return theVal;
}
誰能幫忙,謝謝。
另外,如果有人知道IE8修復程序,則它似乎僅適用於chrome和FF。
我建議使用DataTables jQuery插件來管理排序,搜索,ajax,導出等。 參見http://datatables.net
如果您不能使用服務器,另一種方法可能是添加一個按鈕以將表復制到用戶的剪貼板中以粘貼到excel中。 此步驟解決了標題問題,並為您提供了類似級別的提取背景控制。
您可以簽出一個類似clippy的庫來解決這個問題(github使用它來進行repo url復制)。
您可以使用HTML表導出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.