我尝试使用此Gist中给出的代码将html表导出到excel中。但导出后,当我打开该文件时,它在excel中显示了演示页面的html代码。谁能给出正确的javascript示例用于导出html表格到excel (应在office Calc中打开)。
编辑:附加图片截图。
发布于 2017-05-31 00:13:23
这是我做的一个函数。
在不想在excel中显示的元素上添加"remove“类。
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");
});
https://stackoverflow.com/questions/15563301
复制相似问题