简体   繁体   中英

Export html table to excel using javascript

I tried to export my html table to excel using the code given in this Gist . But after exporting, when i opened the file, It displays the html code of the demo page in excel. Can anyone please give the correct sample of javascript used to export the html table to excel (Should be opened in office Calc too).

EDIT: Attached the image screenshot.

附上图片截图。

Here is a function I made.

Add "remove" class on elements you do not want to show in the 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();
}

Call it on an event, example:

$("#export_button").click(function(e){
    exportExcel("table_id", "filename");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM