Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript将html表格导出到excel_Javascript_Excel_Export To Excel_Html Table - Fatal编程技术网

使用javascript将html表格导出到excel

使用javascript将html表格导出到excel,javascript,excel,export-to-excel,html-table,Javascript,Excel,Export To Excel,Html Table,我尝试使用本文给出的代码将html表导出到excel。但是在导出之后,当我打开文件时,它会在excel中显示演示页面的html代码。任何人都可以提供用于将html表导出到excel的javascript的正确示例(也应该在office Calc中打开) 编辑:附加图像截图 这是我做的一个函数 在不希望在excel中显示的元素上添加“删除”类 function exportExcel(id,name){ //<table> id and filename var today =

我尝试使用本文给出的代码将html表导出到excel。但是在导出之后,当我打开文件时,它会在excel中显示演示页面的html代码。任何人都可以提供用于将html表导出到excel的javascript的正确示例(也应该在office Calc中打开)

编辑:附加图像截图


这是我做的一个函数

在不希望在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();
}

这里的样品很好用。Win7,谷歌浏览器,Office 2007。我注意到,打开文件时会显示excel消息框:“您试图打开的文件‘download.xls’的格式与文件扩展名指定的格式不同。请在打开文件之前确认文件未损坏且来源可靠。是否立即打开文件?”-将文件重命名为download.xlsx导致excel拒绝打开该文件。然而,从目前的情况来看,excel文件看起来与html表格一样,在单元格(2,2)中有蓝色背景,也可能重复@enhzflep-我尝试使用Win XP、Google chrome和Open office。请在编辑中查看附件中的图像。我也在中尝试了该示例。但同样的结果。
$("#export_button").click(function(e){
    exportExcel("table_id", "filename");
});