Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1146324
  • 博文数量: 103
  • 博客积分: 1897
  • 博客等级: 上尉
  • 技术积分: 1717
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-19 21:02
文章分类

全部博文(103)

文章存档

2013年(19)

2012年(84)

分类: JavaScript

2013-01-24 14:27:27

最近在做一个项目,需要在原先的表格的基础上导出excel文件,原先是想用java后台来实现这个功能,但是,后来发现,原来extjs也附带有导出excel表的功能,就在GridPanel的基础上导出,http://www.blogjava.net/rockblue1988/archive/2012/02/29/370977.html,这是我做的时候,参考的一篇网上的文章。具体的做法是,将extjsGridPanel里面的数据拿出来,转换成xml,然后发送给后台,后台响应之后,将数据输出为Excel的格式,具体代码如下。

//利用extjs导出excel文件---begin
	function exportExcel(gridpanel) { //传入的GridPanel的实例
                                var vExportContent = gridpanel.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 : exportExcelGrid,
                                                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);
                            }
                        }
	
	
//利用extjs导出excel文件---end

除此之外,还要引入一个文件

/**
 * 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 	
 *
 */

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 +
            '' +
            '' +
            '' +
            '' +
            '' +
            '' +
            '' +
            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;
    }
});
之后,后台的代码就比较简单了,以下是在strut2下写的。

logger.info("导出excel记录");
	
		ActionContext context = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) context
				.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) context
				.get(ServletActionContext.HTTP_RESPONSE);
		PrintWriter out;
		try {
			out = response.getWriter();
			response.setHeader("Content-Type","application/force-download");
			response.setHeader("Content-Type","application/vnd.ms-excel");
			response.setHeader("Content-Disposition","attachment;filename=export.xls");
			out.print(request.getParameter("exportContent"));

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}
这样一来,就可以实现利用js导出excel文件了。。

exportExcel.rar


阅读(31966) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~