extjs 实现动态导出excel
-
-
我写了一个gridpanel页面,在表格的标题栏可以设置列是否显示 ,现在我想将设置过的页面excel导出, 想要获得将设置的参数在客户端获得然后传到服务器端,判断是否导出列。
现在遇到的问题是,不知道列的是否显示的参数如何获得。请各位大哥大姐帮帮忙啊<
解决方法
cm.isHidden(i)返回定义的cm中,第i列是否显示
显示,返回true,否则返回false.
然后再传到后台去吧.
-
表格的标题栏可以设置列是否显示:我觉得你这个地方可以异步提交个请求,把是否显示保存到服务器去,
或者保存到客户端cookie 在你点击导出时读取-----
难题并不是在怎么提交,而是在怎么获得列的状态(是否显示)
补充一点:
如果默认没有设置是否可见,默认返回好象是undefined.
如果是不可见,则一定是已设置,只能返回true
所以只要是非true的,都是显示的.
学习一下
index.jsp
HTML code
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
index.js
JScript code
Ext.QuickTips.init();Ext.state.Manager.setProvider(new Ext.state.CookieProvider());Ext.onReady(function(){ var store=new Ext.data.JsonStore({ autoLoad : true, url: path+"/servlet/getJsonServlet", fields: ['groupName','groupId','id','text','contacterNumber'] }); var sm = new Ext.grid.CheckboxSelectionModel(); var colM = new Ext.grid.ColumnModel([ new Ext.grid.RowNumberer(), //自动行号 sm, {id:"CMgroupName",header:"所在组",width:200,sortable: true,dataIndex:"groupName"}, {id:"CMtext",header:"姓名",sortable: true,dataIndex:"text"}, {id:"CMcontacterNumber",header:"手机号码",sortable: true,dataIndex:"contacterNumber"} ]); var gridConacterInfo = new Ext.grid.GridPanel({ cm : colM, sm : sm, store : store, autoWidth:true , height : 500, collapsible: true, autoScroll:true, loadMask:true, animCollapse: false, stripeRows: true, // 让 grid 间隔两行的颜色不同 iconCls: 'icon-grid', listeners : { rowdblclick : function( grid , rowIndex , e){ // �������� var record = grid.getStore().getAt(rowIndex); } } }); var win = new Ext.Window({ width: 565, height: 500, layout:'fit', maximizable :true, items:[gridConacterInfo], bbar: [ { xtype:"button", text:"打印", pressed: true, handler:function(){ printit(); } },'','','-','','', { xtype:"button", text:"打印页面设置", pressed: true, handler:function(){ printsetup(); } },'','','-','','', { xtype:"button", text:"打印预览", pressed: true, handler:function(){ printpreview(); } },'','','-','','', { xtype:"button", text:"导入", pressed: true, handler:function(){ alert("导入的操作要从Excel 中获得数据源,在后台拼接 JSON 数据返回到 grid ,并重新加载 store。\n "+ "目前只想到这种方法,使用 JS 方法还需要以后做出来!"); } },'','','-','','', { xtype:"button", text:"导出方法 1", pressed: true, handler:function(){ var vExportContent = gridConacterInfo.getExcelXml(); if (Ext.isIE6 || Ext.isIE7 || Ext.isSafari || Ext.isSafari2 || Ext.isSafari3) { var fd=Ext.get('frmDummy'); if (!fd) { fd=Ext.DomHelper.append(Ext.getBody(), { tag:'form', method:'post', id:'frmDummy', action:'exportexcel.jsp', target:'_blank', name:'frmDummy', cls:'x-hidden', cn:[ { tag:'input', name:'exportContent', id:'exportContent', type:'hidden' } ] },true); } fd.child('#exportContent').set({value:vExportContent}); fd.dom.submit(); } else { document.location = 'data:application/vnd.ms-excel;base64,'+Base64.encode(vExportContent); } } },'','','-','','', { xtype:"button", text:"导出方法 2", pressed: true, handler:function(){ downloadViewData(gridConacterInfo); } },'','','-','','', { xtype:"button", text:"关闭", pressed: true, handler:function(){ win.close(); } } ] }) win.show(); // 导出 Excel 方法2 function downloadViewData(grid) { try { var xls = new ActiveXObject ("Excel.Application"); }catch(e) { alert( "要打印该表,您必须安装Excel电子表格软件,同时浏览器须使用“ActiveX 控件”,您的浏览器须允许执行控件。 请点击【帮助】了解浏览器设置方法!"); return ""; } xls.visible =true; //设置excel为可见 var xlBook = xls.Workbooks.Add; var xlSheet = xlBook.Worksheets(1); var cm = grid.getColumnModel(); var colCount = cm.getColumnCount(); var temp_obj = []; //只下载没有隐藏的列(isHidden()为true表示隐藏,其他都为显示) //临时数组,存放所有当前显示列的下标 for(i=0;i
gridToExcel.js
JScript code
var Base64 = (function() { // Private property var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // Private method for UTF-8 encoding function utf8Encode(string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } // Public method for encoding return { encode : (typeof btoa == 'function') ? function(input) { return btoa(utf8Encode(input)); } : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = utf8Encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return output; } };})();Ext.override(Ext.grid.GridPanel, { getExcelXml: function(includeHidden) { var worksheet = this.createWorksheet(includeHidden); var totalWidth = this.getColumnModel().getTotalWidth(includeHidden); return '' + '' + '' + this.title + ' ' + '' + '' + worksheet.height + ' ' + '' + worksheet.width + ' ' + 'False ' + 'False ' + ' ' + '' + '' + ' ' + ' ' + '' + ' ' + ' ' + ' ' + ' ' + ' ' + ' ' + ' ' + ' ' + ' ' + '' + ' ' + ' ' + ' ' + ' ' + ' ' + '' + ' ' + ' ' + ' ' + ' ' + '' + ' ' + ' ' + '' + ' ' + ' ' + '' + ' ' + ' ' + '' + ' ' + ' ' + '' + ' ' + ' ' + '' + ' ' + ' ' + '' + ' ' + ' ' + '' + ' ' + ' ' + ' ' + worksheet.xml + ' '; }, createWorksheet: function(includeHidden) { // Calculate cell data types and extra class names which affect formatting var cellType = []; var cellTypeClass = []; var cm = this.getColumnModel(); var totalWidthInPixels = 0; var colXml = ''; var headerXml = ''; var visibleColumnCountReduction = 0; var colCount = cm.getColumnCount(); for (var i = 0; i < colCount; i++) { if ((cm.getDataIndex(i) != '') && (includeHidden || !cm.isHidden(i))) { var w = cm.getColumnWidth(i) totalWidthInPixels += w; if (cm.getColumnHeader(i) === ""){ cellType.push("None"); cellTypeClass.push(""); ++visibleColumnCountReduction; } else { colXml += ' '; headerXml += '' + '' + cm.getColumnHeader(i) + ' ' + ' '; var fld = this.store.recordType.prototype.fields.get(cm.getDataIndex(i)); switch(fld.type) { case "int": cellType.push("Number"); cellTypeClass.push("int"); break; case "float": cellType.push("Number"); cellTypeClass.push("float"); break; case "bool": case "boolean": cellType.push("String"); cellTypeClass.push(""); break; case "date": cellType.push("DateTime"); cellTypeClass.push("date"); break; default: cellType.push("String"); cellTypeClass.push(""); break; } } } }
紧接上面 js 代码
JScript code
var visibleColumnCount = cellType.length - visibleColumnCountReduction; var result = { height: 9000, width: Math.floor(totalWidthInPixels * 30) + 50 }; // Generate worksheet header details. var t = '' + '' + ' ' + ' ' + '' + colXml + '' + '' + '' + ''+ this.title +' ' + ' ' + ' ' + '' + headerXml + ' '; // Generate the data rows from the data in the Store for (var i = 0, it = this.store.data.items, l = it.length; i < l; i++) { t += ''; var cellClass = (i & 1) ? 'odd' : 'even'; r = it[i].data; var k = 0; for (var j = 0; j < colCount; j++) { if ((cm.getDataIndex(j) != '') && (includeHidden || !cm.isHidden(j))) { var v = r[cm.getDataIndex(j)]; if (cellType[k] !== "None") { t += ''; if (cellType[k] == 'DateTime') { t += v.format('Y-m-d'); } else { t += v; } t +=' '; } k++; } } t += ' '; } result.xml = t + ' ' + '' + '' + ' ' + ' ' + ' ' + ' ' + ' ' + '' + 'Blank ' + '1 ' + '32767 ' + ' ' + '600 ' + ' ' + ' ' + ' ' + 'False ' + 'False ' + ' ' + ' '; return result; }});
我也实现了,贴出来与大家共享一下
function checkColumn(){
var i = 0;
var colStr = ',';
for(i=0;i {
var cm = grid.colModel.config[i];
if(cm.dataIndex!=''&&!cm.hidden) // 判断列标识不为空,并且不是hidden
{
//alert(cm.dataIndex +' '+ cm.header); //可以获得 其index,及header 参见 grid的定义;
colStr = colStr + cm.dataIndex +",";
}
}
Ext.get('exp_column').dom.value = colStr; //exp_column,是定义在form表单里的一个hidden类型的input对象,form表单提交之前先把该值给初始化一下
}
本篇文章来源于 www.phpzy.com 原文链接:http://www.phpzy.com/php/803718.html