简体   繁体   English

使用JavaScript将HTML表格导出到Excel

[英]Export html table to excel using javascript

I tried to export my html table to excel using the code given in this Gist . 我试图使用此Gist中给出的代码将html表导出为ex​​cel。 But after exporting, when i opened the file, It displays the html code of the demo page in excel. 但是导出后,当我打开文件时,它将在excel中显示演示页面的html代码。 Can anyone please give the correct sample of javascript used to export the html table to excel (Should be opened in office Calc too). 任何人都可以将用于导出html表的javascript正确示例提供给excel(也应在office Calc中打开)。

EDIT: Attached the image screenshot. 编辑:附加图像截图。

附上图片截图。

Here is a function I made. 这是我做的功能。

Add "remove" class on elements you do not want to show in the excel. 在不想显示在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();
}

Call it on an event, example: 在事件上调用它,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM