纯js的excel导出插件

本文介绍了一种在不牺牲服务器性能的情况下,将前端Table内容转换并导出为Excel文件的方法。通过使用自定义JavaScript插件,可以轻松实现网页表格到Excel的转换,并提供了具体的实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在不影响服务器性能的前提下前端导出table内容为excel文件


/**
使用示例 自动绑定 table_to_excel
<a href="#" download="交易记录.xls"class="to_excel fjgl_top_r_05">导出</a>

$(".to_excel").click(function(event){
	var t = Itable2excel({
		worksheet:'数据分析',
		table: $('#order-list table')
	});
	var data64 = t.uri();
	if(data64==false)
		return false;
	event.currentTarget.href = data64;
});


 */
(function($,win,dom,undef){

	var tmp  = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"></meta><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{{worksheet}}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>{{tables}}</body></html>';

	var Itable2excel=function(settings){
		this.settings = $.extend({},Itable2excel.defaults,settings);
		this.template = '';
		//this.data64 = '';
		//执行
		this.run=function(){
			this.exportHandler();
			return this;
		}
	};

	/**
	 * 弹出框 默认配置 可扩展
	 * @type {Object}
	 */
	Itable2excel.defaults={
		worksheet:'Worksheet',
		table:[],
	};

	Itable2excel.prototype={
		//输出base64的excel下载资源
		uri:function() {
			if($(this.template).find('tbody tr').length==0)
				return false;
			var	uri = 'data:application/vnd.ms-excel;base64,';
				return uri + this.base64();
		},

		base64:function() {
			return window.btoa(unescape(encodeURIComponent(this.template)));

		},
		//对话框本身事件绑定
		exportHandler:function(){
			var table_str = '';
			//数据过滤
			$.each( this.settings.table, function(i){
				var t = $('<div><table><thead></thead><tbody></tobdy></table></div>');
				t.find('thead').html($(this.tHead).html());
				t.find('tbody').append($(this.tBodies).children(':visible').clone());
				t.find('.not-print').remove(); 			// not-print 是@media print中不会打印的部分
				t.find('img').remove();					//图片过滤
				t.find('.table_search').remove(); 		//搜索栏过滤
				
				t.find('a').replaceWith(function (i) { 	//表格中不再需要的超链接也移除
					return this.innerHTML;
				});
				table_str +=t.html();
			});
			this.template = tmp.replace(/\{\{tables\}\}/g, table_str);
			this.template = this.template.replace(/\{\{worksheet\}\}/g, this.settings.worksheet);
		},
	};



	win['Itable2excel']=function(settings){
		var obj = new Itable2excel(settings);
		return obj.run();
	};


})(jQuery,window,document);

技术指导

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值