首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用javascript将html表导出到excel

使用javascript将html表导出到excel
EN

Stack Overflow用户
提问于 2013-03-22 13:24:02
回答 1查看 3.5K关注 0票数 2

我尝试使用此Gist中给出的代码将html表导出到excel中。但导出后,当我打开该文件时,它在excel中显示了演示页面的html代码。谁能给出正确的javascript示例用于导出html表格到excel (应在office Calc中打开)。

编辑:附加图片截图。

EN

回答 1

Stack Overflow用户

发布于 2017-05-31 00:13:23

这是我做的一个函数。

在不想在excel中显示的元素上添加"remove“类。

代码语言:javascript
运行
复制
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();
}

在事件上调用它,例如:

代码语言:javascript
运行
复制
$("#export_button").click(function(e){
    exportExcel("table_id", "filename");
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15563301

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档