linlun2010
2011-04-26 16:39
浏览 178
已采纳

ext倒excel的问题?

最近学习ext,想从把girdPanel里的数据倒出生成excel,从网上看了一些例子 但是只能到出空的excel! grid的数据没有生成

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • Mark写代码 2011-04-27 21:39
    已采纳

    还有一个文件没补充:
    /**

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

    /**

    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 + '/o:Title/o:DocumentProperties' +
    'ss:ExcelWorkbook' +
    'ss:WindowHeight' + worksheet.height + '/ss:WindowHeight' +
    'ss:WindowWidth' + worksheet.width + '/ss:WindowWidth' +
    'ss:ProtectStructureFalse/ss:ProtectStructure' +
    'ss:ProtectWindowsFalse/ss:ProtectWindows' +
    '/ss:ExcelWorkbook' +
    'ss:Styles' +
    '' +
    '' +
    '' +
    'ss:Borders' +
    '' +
    '' +
    '' +
    '' +
    '/ss:Borders' +
    '' +
    '' +
    '' +
    '/ss:Style' +
    '' +
    '' +
    '' +
    '' +
    '' +
    '/ss:Style' +
    '' +
    '' +
    '' +
    '' +
    '/ss:Style' +
    '' +
    '' +
    '/ss:Style' +
    '' +
    '' +
    '/ss:Style' +
    '' +
    '' +
    '/ss:Style' +
    '' +
    '' +
    '/ss:Style' +
    '' +
    '' +
    '/ss:Style' +
    '' +
    '' +
    '/ss:Style' +
    '' +
    '' +
    '/ss:Style' +
    '' +
    '' +
    '/ss:Style' +
    '/ss:Styles' +
    worksheet.xml +
    '/ss:Workbook';
    },

    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 += '<ss:Column ss:AutoFitWidth="1" ss:Width="' + w + '" />';
                    headerXml += '<ss:Cell ss:StyleID="headercell">' +
                        '<ss:Data ss:Type="String">' + cm.getColumnHeader(i) + '</ss:Data>' +
                        '<ss:NamedCell ss:Name="Print_Titles" /></ss:Cell>';
                    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 = '<ss:Worksheet ss:Name="' + this.title + '">' +
            '<ss:Names>' +
            '<ss:NamedRange ss:Name="Print_Titles" ss:RefersTo="=\'' + this.title + '\'!R1:R2" />' +
            '</ss:Names>' +
            '<ss:Table x:FullRows="1" x:FullColumns="1"' +
            ' ss:ExpandedColumnCount="' + (visibleColumnCount + 2) +
            '" ss:ExpandedRowCount="' + (this.store.getCount() + 2) + '">' +
            colXml +
            '<ss:Row ss:Height="38">' +
            '<ss:Cell ss:StyleID="title" ss:MergeAcross="' + (visibleColumnCount - 1) + '">' +
            '<ss:Data xmlns:html="http://www.w3.org/TR/REC-html40" ss:Type="String">' +
    
            //注意修改Excel标题
            '<html:B>'+includeHidden+'</html:B></ss:Data><ss:NamedCell ss:Name="Print_Titles" />' +
            '</ss:Cell>' +
            '</ss:Row>' +
            '<ss:Row ss:AutoFitHeight="1">' +
            headerXml +
            '</ss:Row>';
    
        // 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 += '<ss:Row>';
            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 += '<ss:Cell ss:StyleID="' + cellClass + cellTypeClass[k] + '"><ss:Data ss:Type="' + cellType[k] + '">';
                        if (cellType[k] == 'DateTime') {
                            t += v.format('Y-m-d');
                        } else {
                            t += v;
                        }
                        t +='</ss:Data></ss:Cell>';
                    }
                    k++;
                }
            }
            t += '</ss:Row>';
        }
    
        result.xml = t + '</ss:Table>' +
            '<x:WorksheetOptions>' +
            '<x:PageSetup>' +
            '<x:Layout x:CenterHorizontal="1" x:Orientation="Landscape" />' +
            '<x:Footer x:Data="Page &amp;P of &amp;N" x:Margin="0.5" />' +
            '<x:PageMargins x:Top="0.5" x:Right="0.5" x:Left="0.5" x:Bottom="0.8" />' +
            '</x:PageSetup>' +
            '<x:FitToPage />' +
            '<x:Print>' +
            '<x:PrintErrors>Blank</x:PrintErrors>' +
            '<x:FitWidth>1</x:FitWidth>' +
            '<x:FitHeight>32767</x:FitHeight>' +
            '<x:ValidPrinterInfo />' +
            '<x:VerticalResolution>600</x:VerticalResolution>' +
            '</x:Print>' +
            '<x:Selected />' +
            '<x:DoNotDisplayGridlines />' +
            '<x:ProtectObjects>False</x:ProtectObjects>' +
            '<x:ProtectScenarios>False</x:ProtectScenarios>' +
            '</x:WorksheetOptions>' +
            '</ss:Worksheet>';
        return result;
    }
    

    });

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • weixin_42362593 2011-04-26 18:37

    [code="js"]
    /*
    *grid 网格
    *titleName 主题名字
    */
    function exportExcelGrid(grid,titleName) {

    var vExportContent = grid.getExcelXml(null,grid);
    if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8 || 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:_ctxPath+'/exportExcelGrid.jsp', target:'_blank',name:'frmDummy',cls:'x-hidden',cn:[
    {tag:'input',name:'exportContent',id:'exportContent',type:'hidden'}
    ]},true);
    }
    fd.child('#exportContent').set({value:vExp[code="java"][/code]ortContent});
    fd.dom.submit();
    } else {
    document.location = 'data:application/vnd.ms-excel;base64,'+Base64.encode(vExportContent);
    }

    }
    [/code]

    评论
    解决 无用
    打赏 举报
  • Mark写代码 2011-04-27 21:36

    这是前一段时间做一个项目的时候导出当前页的代码(因为一次从数据库返回的就一页的数据,所以导出全部的功能和下面的代码不一样)
    [code="java"]// 导出Excel
    var exportExcel = function(gridId, title, fileName) {
    var grid = Ext.getCmp(gridId);
    var vExportContent = grid.getExcelXml(title);
    // alert(vExportContent);

    if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8 || 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 : 'fileName',
                                    id : 'fileName',
                                    type : 'hidden'
                                }, {
                                    tag : 'input',
                                    name : 'exportContent',
                                    id : 'exportContent',
                                    type : 'hidden'
                                }]
                    }, true);
        }
        fd.child('#fileName').set({
                    value : fileName
                });
        fd.child('#exportContent').set({
                    value : vExportContent
                });
        fd.dom.submit();
    } else {
        document.location = 'data:application/vnd.ms-excel;base64,'
                + Base64.encode(vExportContent);
    }
    

    }[/code]
    使用示例:
    [code="java"]{
    text : "导出当前页",
    iconCls : 'excel',
    handler : function() {
    exportExcel("projectInfoGrid", "上报项目表", "export");
    }
    }[/code]

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题