ExtJS导出Excel表格详解

ExtJs导出Excel表格

源文件引入工程:girdToExcel.js

 

/**
 * allows for downloading of grid data (store) directly into excel
 * Method: extracts data of gridPanel store, uses columnModel to construct XML excel document,
 * converts to Base64, then loads everything into a data URL link.
 *
 * @author		Animal		
 *
 */

/**
 * base64 encode / decode
 *
 * @location 	http://www.webtoolkit.info/
 *
 */

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;
                    }
                }
            }
        }
        var visibleColumnCount = cellType.length - visibleColumnCountReduction;

        var result = {
            height: 9000,
            width: Math.floor(totalWidthInPixels * 30) + 50
        };

        // Generate worksheet header details.
        var t = '' +
            '' +
            '' +
            '' +
            '' +
            colXml +
            '' +
            '' +
            '' +
            'ESB_监控主表' +
            '' +
            '' +
            '' +
            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;
    }
});

第一步:确定你的gird能在IE正常打开

第二步:引入此代码(自己更改)

<%@ page contentType="text/html;charset=GBK" %>
<%@ include file="/include/includeHead.jsp" %>





第三步:添加 导出Excel按钮:

在你的gird代码内添加一下代码:

                      tbar : [{
			text : "导出EXCEL",
			iconCls : 'page_excelIcon',
			handler : function(title,fileName) {
				var vExportContent = grid.getExcelXml(title); // 获取数据(一般这里会报错,那就看你源文件引入的对吗?)
				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 : 'newExportExcel.jsp',
						target : '_blank',
						name : 'frmDummy',
						cls : 'x-hidden',
						cn : [
						 {tag:'input',name:'fileName',id:'fileName',type:'hidden'},
						 {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);
                                                                //(一般这里会报错,那就看你源文件引入的对吗?)Bat64 not isfounction

}}}],

 
   

第四步,添加一个jsp引入文件(没有此文件 Excel 不能按照此方式导出)newExportExcel.jsp(路径是在同一文件内)

<%@ page language="java" pageEncoding="UTF-8"%>
<%
String content = request.getParameter("exportContent");
String fileName = request.getParameter("fileName");
content = new String(content.getBytes("ISO8859_1"));
fileName="ESB_MONITORLIST";
response.setHeader("Content-Type","application/force-download");
response.setHeader("Content-Type","application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment;filename="+fileName+".xls");
out.print(content);

%>

 

 
   

 

 

网上流传的很多版本在ie7、ie8中导出中文是乱码ff可以不乱码,需要在jsp文件中加上<%@ page language="java" pageEncoding="UTF-8"%>头,获取的内容需要进行转码:content = new String(content.getBytes("ISO8859_1")); 这样在ie7、ie8、Firefox中都可以导出中文。

只要按照我说的一步一步来这时候就应该能导出了 ,乱码问题在上文我已经解决。

我在网上还找到了一个一个文件 提供大家参考

 

<%@ page language="java" pageEncoding="UTF-8"%>
<%@page import= "java.net.URLEncoder "%> 
<% 
	request.setCharacterEncoding("GBK");
	String content = request.getParameter("exportContent");
	String fileName = request.getParameter("fileName");
	String os = System.getProperty("os.name");
	
	if(os.contains("Windows")){
	   content = new String(content.getBytes("ISO8859_1"));//WINDOWS 下需要进行转码,AIX下不需要转码
	}else if(os.contains("AIX")){
		fileName = java.net.URLEncoder.encode(fileName,"UTF-8");//WINDOWS 下不需要对文件名进行转码,AIX下需要转码
	}
	
	response.setHeader("Content-Type","application/force-download");
	response.setHeader("Content-Type","application/vnd.ms-excel");
	response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xls");
	out.print(content); 

%> 


关于JSP形式导出Excel 就这么多了.....

你可能感兴趣的:(ExtJs)