使用javascript将html表导出为ex​​cel

时间:2013-03-22 05:24:02

标签: javascript excel export-to-excel html-table

我尝试使用此Gist中给出的代码将我的html表导出为ex​​cel。但导出后,当我打开文件时,它会在excel中显示演示页面的html代码。任何人都可以提供正确的javascript示例用于将html表导出为ex​​cel(也应该在办公室Calc中打开)。

编辑:附上图片截图。

Attached the image screenshot.

1 个答案:

答案 0 :(得分:0)

这是我做的一个功能。

在您不希望在Excel中显示的元素上添加“删除”类。

function exportExcel(id,name){ //<table> id and filename
    var today = new Date();
    var date = ('0'+today.getDate()).slice(-2)+"-"+('0'+(today.getMonth()+1)).slice(-2)+"-"+today.getFullYear();

    var file_name = name+"_"+date+".xls"; //filename with current date, change if needed
    var meta = '<meta http-equiv="content-type" content="text/html; charset=UTF-8" />';
    var html = $("#"+id).clone();

    html.find('.remove').remove(); //add the 'remove' class on elements you do not want to show in the excel
    html.find('a').each(function() { //remove links, leave text only
        var txt = $(this).text();
        $(this).after(txt).remove();
    });
    html.find('input, textarea').each(function() { //replace inputs for their respectives texts
        var txt = $(this).val().replace(/\r\n|\r|\n/g,"<br>");
        $(this).after(txt).remove();
    });
    html.find('select').each(function() { //replace selects for their selected option text
        var txt = $(this).find('option:selected').text();
        $(this).after(txt).remove();
    });
    html.find('br').attr('style', "mso-data-placement:same-cell"); //make line breaks show in single cell
    html = "<table>"+html.html()+"</table>";

    var uri = 'data:application/vnd.ms-excel,'+encodeURIComponent(meta+html);
    var a = $("<a>", {href: uri, download: file_name});
    $(a)[0].click();
}

在事件上调用它,例如:

$("#export_button").click(function(e){
    exportExcel("table_id", "filename");
});