日期:2014-05-16  浏览次数:20377 次

Extjs Grid导出表格 功能实现
1、基本原理是:客户端根据Grid数据、使用ExportExcel.js文件生成Excel格式的XML数据,然后发送到一个服务端文件(ExportExcel.jsp),服务端文件通过设定Content-Type来实现Excel的下载。

2、导出Excel按钮代码:

{
    text:"导出Excel",
    icon : "../images/icon/upload.png",
    handler : ExcelExport
   }

function ExcelExport() {
  var vExportContent = grid.getExcelXml(); // 获取数据
  if (Ext.isIE8 ||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);
  }

}

2、ExportExcel.js源码:

var Base64 = (function() {
// Private property
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

// 局部方法中文编码
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;
}

// 公共方法
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;
}
};
})();
//设置xml文件格式
Ext.override(Ext.grid.GridPanel, {
getExcelXml: function(includeHidden) {
var worksheet = this.createWorksheet(includeHidden);
var totalWidth = this.getColumnModel().getTotalWidth(includeHidden)