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

Hea*_*Way 8 html javascript excel 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))
  }
})()
Run Code Online (Sandbox Code Playgroud)

这是我的提交按钮:

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

我遇到的问题是我的一些输入是下拉和输入,但它们在构建excel文件时是隐藏的.因此,当excel文件首次构建时,您将看到所有数据,并且在2秒内所有具有隐藏下拉列表和输入的数据都将变为空白并呈现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();
Run Code Online (Sandbox Code Playgroud)
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;

} 
Run Code Online (Sandbox Code Playgroud)

谁能伸出援手,谢谢你.

此外,如果有人知道IE8修复,它似乎只适用于chrome和FF.

Dan*_*nor 0

如果您无法使用服务器,另一种方法可能是添加一个按钮,将表复制到用户的剪贴板,然后粘贴到 Excel 中。这解决了标头问题,并为您提供了对提取的类似级别的后台控制。

您可以查看像Clippy这样的库来协助完成此操作(github 使用它来复制存储库 URL)。