【问题标题】:Export html table to excel using javascript使用javascript将html表导出到excel
【发布时间】:2013-03-11 21:27:23
【问题描述】:

我尝试使用Gist 中给出的代码将我的 html 表导出到 excel。但是导出后,当我打开文件时,它会在 excel 中显示演示页面的 html 代码。谁能提供正确的用于将 html 表导出到 excel 的 javascript 示例(也应该在办公室 Calc 中打开)。

编辑:附上图片截图。

【问题讨论】:

  • 示例在这里工作得很好。 Win7,Google Chrome,Office 2007。我确实注意到,打开文件时显示的 excel 消息框:“您尝试打开的文件‘download.xls’的格式与文件扩展名指定的格式不同。验证在打开文件之前确认文件没有损坏并且来自受信任的来源。现在要打开文件吗? - 将文件重命名为 download.xlsx 导致 excel 拒绝打开它。但是,就目前而言,excel 文件看起来与 html 表格相同,在 cell(2,2) 中具有蓝色背景
  • @enhzflep - 我尝试使用 Win XP、Google chrome、Open office。请在编辑中查看附件图片。
  • 我也试过this link中的例子。但结果相同。

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


【解决方案1】:

这是我做的一个函数。

在您不想在 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");
});

【讨论】:

    猜你喜欢
    • 2014-06-20
    • 2017-05-10
    • 2013-06-13
    • 2011-09-27
    • 2023-03-27
    • 2012-03-10
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多