[英]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.