多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
使用extjs肯定少不了使用表格控件,用到表格,领导们(一般)还是惯于使用excel看数据,所以用到extjs表格的技术猿们肯定也会有导出表格excel这一个需求,本文主要针对如何在用extjs将grid表格导出到excel,使用的是前端导出,不涉及后端。 - - [源代码打包下载](#) - [将源代码嵌入到应用中](#) - [查看导出按钮以及导出效果](#) - [扩展支持sum统计和groupsum分组](#) ### 源代码打包下载 本次使用的是github上的一个开源项目Exporter 下载地址:[https://github.com/iwiznia/Ext.ux.Exporter](https://github.com/iwiznia/Ext.ux.Exporter) 下载之后,可以看到文件目录是这样的(已经是4年前维护的项目了): ![项目概述](https://box.kancloud.cn/2016-02-03_56b215dac1c30.jpg "") ### 将源代码嵌入到应用中 要实现功能的话,这里面的所有文件都要加到项目中的。 然后,需要在使用导出的页面上加入这个js文件的引入: `<script type="text/javascript" src="<%=context %>/pages/yourpathtojsppage/export-all.js"> </script>` 在extjs的onready之前引入如下所需: ~~~ Ext.Loader.setConfig({ enabled: true }); Ext.Loader.setPath('Ext.ux.exporter', 'exporter'); Ext.require([ 'Ext.ux.exporter.Exporter' ]); ~~~ grid定义的时候加上导出excel的入口: ~~~ var grid = Ext.create('Ext.grid.Panel', { frame: true, title: 'test', columnLines: true, // 加上表格线 height: 800, features: [{ ftype: 'summary' }], columns: [{yourclolunms}], store: ytkbbStore, dockedItems: [{ xtype: 'toolbar', dock: 'top', items: [{xtype: 'exporterbutton',store: yourStore}] }], renderTo: Ext.getBody() ~~~ }); 这样,就实现了将导出excel的功能嵌入到了应用程序中。 ### 查看导出按钮以及导出效果 查看grid表格,发现已增加按钮,如图: ![这里写图片描述](https://box.kancloud.cn/2016-02-03_56b215dae7511.jpg "") | 时间 | 费用 | kg | |-----|-----|-----| | 2014-03 | 227 | 1882.74 | | 2014-04 | 146 | 1200.12 | | 2014-05 | 187 | 1561.27 | | 2014-06 | 111 | 930.18 | | 2014-07 | 50 4 | 33.5 | | 2014-08 | 150 | 1267.5 | | 2014-09 | 164 | 1343.75 | | 2014-10 | 134 | 1070.66 | 导出之后的excel截图如下: ![这里写图片描述](https://box.kancloud.cn/2016-02-03_56b215db00c80.jpg "") 可以看到正确进行了数据导出. ### 扩展支持sum统计和groupsum分组 > 技巧:对worksheet.js 进行修改可以调整表格设置,表格内容的出来都是在这里。 //增加合计行 if (this.hasSum){ var style; Ext.each(this.columns, function(col,index,self) { style = ‘odd’; if (col.summaryType==”sum”){ var v = this.store.sum(col.dataIndex); cells.push(this.buildCell(‘合计: ’ + v, ‘String’, style).render()) }else{ cells.push(this.buildCell(”, ‘String’, style).render()) } }, this); rows.push(Ext.String.format(“{0}”, cells.join(“”))); }; 以上是对最后一个统计行的处理。 //分组合计行 buildGroupSumRow: function(me, groupkey, store) { var style,cells = []; if (me.stripeRows === true) style = ‘odd’; type = ‘String’; var insertRow = function(me){ Ext.each(me.columns, function (col, dataIndex) { if (!col.groupSumField){ cells.push(me.buildCell(”, type, style).render()); }else{ var abc = store.getGroups().getByKey( groupkey );//sumByGroup(store.groupField); var sumabc = abc.sum(col.dataIndex); cells.push(me.buildCell(‘合计: ‘+sumabc, type, style).render()); } }); return Ext.String.format(“{0}”, cells.join(“”)); }; return insertRow(this); } 以上是处理分组的,可以实现sum方法合计也可以取平均值等。OK到现在就可以正确的导出表格数据到excel了。