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

我试图导出我的HTML表格,以Excel中给出的代码在这个GIST 。 但是在导出之后,当我打开文件的时候,它在excel中显示演示页面的html代码。 任何人都可以给正确的JavaScript样本用于导出的HTML表格,以Excel(应在办公室计算器也打开)。

编辑:附上图像截图。

附上图片截图。

这是我做的一个function。

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