使用extjs肯定少不了使用表格控件,用到表格,領導們(一般)還是慣於使用excel看數據,所以用到extjs表格的技術猿們肯定也會有導出表格excel這一個需求,本文主要針對如何在用extjs將grid表格導出到excel,使用的是前端導出,不涉及後端。
源代碼打包下載
本次使用的是github上的一個開源項目Exporter
下載地址:https://github.com/iwiznia/Ext.ux.Exporter
下載之後,可以看到文件目錄是這樣的(已經是4年前維護的項目了):
將源代碼嵌入到應用中
要實現功能的話,這裏面的所有文件都要加到項目中的。
然後,需要在使用導出的頁面上加入這個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表格,發現已增加按鈕,如圖:
時間 | 費用 | 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截圖如下:
可以看到正確進行了數據導出.
擴展支持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了。