使用jQuery将表格数据导出为ex​​cel

我正在使用这个代码:

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)) } })() 

这是我的提交button:

 <td><input type="button" onclick="tableToExcel('project_table', 'W3C Example Table')" value="Export to Excel"></td> 

我遇到的问题是我的一些input是下拉菜单和input,但它们隐藏在构buildexcel文件的时候。 所以,当excel文件第一次build立时,你会看到所有的数据,在2秒钟内,所有的隐藏下拉列表和input后面的数据变成空白,并呈现HTML。

PIC1:

输入字段消失

PIC2:

隐藏的元素

我试图使用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修复,它似乎只能在铬和FF工作。

我build议使用DataTables jQuery插件来pipe理sorting,search,ajax,出口和更多。 请参阅http://datatables.net

如果你不能使用服务器,另一种方法可能是添加一个button,将表复制到用户的剪贴板粘贴到Excel中。 这一方面的步骤头问题,并给你一个类似的背景控制水平的提取。

你可以看看像clippy这样的lib来协助(github使用它来进行repo url复制)。