export html to excel,Export html table to excel using javascript

Here is a function I made.

Add "remove" class on elements you do not want to show in the excel.

function exportExcel(id,name){ //

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 = '';

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,"
");

$(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 = "

";

var uri = 'data:application/vnd.ms-excel,'+encodeURIComponent(meta+html);

var a = $("", {href: uri, download: file_name});

$(a)[0].click();

}

Call it on an event, example:

$("#export_button").click(function(e){

exportExcel("table_id", "filename");

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值