代码之家  ›  专栏  ›  技术社区  ›  Dipin Kumar

将数据网格导出到excel

  •  0
  • Dipin Kumar  · 技术社区  · 13 年前

    我创建了一个数据网格,还创建了一些文本框和数据网格外的提交按钮。。如果我们在文本框中输入一些数据,然后单击提交按钮,则数据将存储到数据网格中。。我想把这些数据从数据网格导出到excel中。怎么可能?我如何创建excel工作表,以及它如何与我的数据网格连接? 我的代码如下

    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
                   xmlns:s="library://ns.adobe.com/flex/spark" 
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="application1_creationCompleteHandler(event)">
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
        <fx:Script>
            <![CDATA[
                import com.as3xls.xls.Sheet;
    
                import mx.collections.ArrayCollection;
                import mx.controls.Alert;
                import mx.effects.easing.Exponential;
                import mx.events.FlexEvent;
    
    
                [Bindable]
                public var dgItems_client:ArrayCollection = new ArrayCollection();
                public var dgItems_admin:ArrayCollection = new ArrayCollection();
                public var temp_client:Object = new Object();
                public var temp_admin:Object = new Object();
                private var fileRef:FileReference=new FileReference;
                private var sheet:Sheet;
                //          public var imagegrid:Image;
                private function tabChange():void
                {
                    errorAdmin.visible=false;
                    errorClient.visible=false;
                    if(gh.selectedChild.name=='clientTab')
                    {
                        details.dataProvider=dgItems_client;
                        arrayName.headerText="Client_Name";
                    }
                    else
                    {
                        details.dataProvider=dgItems_admin;
                        arrayName.headerText="Admin_Name";
                    }
                }
                private function submitClick():void
                {
                    if(name_client.text!="" && address_client.text!="" && phone_client.text!="")
                    {
    
                        temp_client = ({Name:name_client.text, Address:address_client.text,Phone_Number:phone_client.text});
                        dgItems_client.addItem(temp_client);
                        name_client.text="";
                        address_client.text="";
                        phone_client.text="";
                        clientClick();
                        errorClient.visible=false;
                    }
                    else
                    {
                        errorClient.visible=true;
                    }
                    if(name_admin.text!=""&&address_admin.text!=""&&phone_admin.text!="")
                    {
                        temp_admin = ({Name:name_admin.text, Address:address_admin.text,Phone_Number:phone_admin.text});
                        dgItems_admin.addItem(temp_admin);
                        name_admin.text="";
                        address_admin.text="";
                        phone_admin.text="";
                        errorAdmin.visible=false;
                    }
                    else
                    {
                        errorAdmin.visible=true;
                    }
    
                }
                private function clientClick():void
                {
    
                    details.dataProvider=dgItems_client;
                    arrayName.headerText="Client_Name";
                }
                private function adminClick():void
                {
    
                    details.dataProvider=dgItems_admin;
                    arrayName.headerText="Admin_Name";
                }
                protected function application1_creationCompleteHandler(event:FlexEvent):void
                {
                    fileRef.addEventListener(Event.SELECT,fileSelected);
    
                }
                private function fileSelected():void
                {
    
                }
                private function executeExport():void
                {
                     sheet=new Sheet;
    //               var dataProviderCollection:ArrayCollection;
                    var rowCount:int=details.columnsLength;
                    Alert.show(rowCount.toString());
                }
    
            ]]>
        </fx:Script>
        <mx:TabNavigator x="27" y="11" width="455" height="376" id="gh" change="tabChange()" backgroundColor="#A4B6E9">
            <s:NavigatorContent width="100%" height="100%" label="Client" id="clientTab">
                <s:Label x="10" y="30" width="52" height="25" text="Name:"/>
                <s:Label x="10" y="127" width="52" height="28" text="Address:"/>
                <s:TextInput id="name_client" x="69" y="18" width="188" height="37" restrict="a-zA-Z"/>
                <s:TextArea id="address_client" x="70" y="70" height="126"/>
                <s:Label x="10" y="230" width="84" height="32" text="Phone:"/>
                <s:TextInput id="phone_client" x="70" y="218" width="188" height="30" restrict="0-9" maxChars="10"/>
                <s:Button x="100" y="291" height="28" label="Submit"  click="submitClick()"/>           
                <s:Label id="errorClient" x="59" y="270" width="171" height="27" text="please fill the blank fields" color="red" visible="false"/>
            </s:NavigatorContent>
            <s:NavigatorContent width="100%" height="100%" label="Admin" id="adminTab" >
                <s:Label x="23" y="48" width="52" height="25" text="Name:"/>
                <s:Label x="26" y="148" width="52" height="28" text="Address:"/>
                <s:TextInput id="name_admin" x="105" y="33" width="188" height="37"/>
                <s:TextArea id="address_admin" x="105" y="93" height="126"/>
                <s:Label x="26" y="257" width="84" height="32" text="Phone:"/>
                <s:TextInput id="phone_admin" x="104" y="246" width="188" height="30" restrict="0-9" maxChars="10"/>
                <s:Button x="137" y="305" height="28" label="Submit" click="submitClick()"/>
                <s:Label id="errorAdmin" x="100" y="286" width="171" height="17" color="red" fontSize="14"
                         text="please fill the blank fields" visible="false"/>
                <s:Button x="335" y="60" height="34" label="Admin Details" click="adminClick()"/>
                <s:Button x="335" y="180" height="34" label="Client Details" click="clientClick()"/>
    
            </s:NavigatorContent>
        </mx:TabNavigator>
        <s:TitleWindow x="521" y="84" width="377" height="234">
            <s:DataGrid x="0" y="0" width="375" height="163" borderVisible="true" id="details">
                <s:columns>
                    <s:ArrayList>
                        <s:GridColumn dataField="Name" id="arrayName"></s:GridColumn>
                        <s:GridColumn dataField="Address" headerText="Address"></s:GridColumn>
                        <s:GridColumn dataField="Phone_Number" headerText="Phone_Number"></s:GridColumn>
                    </s:ArrayList>
                </s:columns>
            </s:DataGrid>
            <s:Button x="139" y="167" height="28" label="Export" click="executeExport()"/>
        </s:TitleWindow>
    </s:Application>
    
    1 回复  |  直到 13 年前
        1
  •  1
  •   Mahesh Parate    13 年前

    好啊 您可以尝试以下代码:-

    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
                   xmlns:s="library://ns.adobe.com/flex/spark" 
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" 
                   >
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
        <fx:Script>
            <![CDATA[
                import com.as3xls.xls.Sheet;
    
                import mx.collections.ArrayCollection;
                import mx.controls.Alert;
                import mx.effects.easing.Exponential;
                import mx.events.FlexEvent;
    
    
                [Bindable]
                public var dgItems_client:ArrayCollection = new ArrayCollection();
                public var dgItems_admin:ArrayCollection = new ArrayCollection();
                public var temp_client:Object = new Object();
                public var temp_admin:Object = new Object();
    
                private function tabChange():void
                {
                    errorAdmin.visible=false;
                    errorClient.visible=false;
                    if(gh.selectedChild.name=='clientTab')
                    {
                        details.dataProvider=dgItems_client;
                        arrayName.headerText="Client_Name";
                    }
                    else
                    {
                        details.dataProvider=dgItems_admin;
                        arrayName.headerText="Admin_Name";
                    }
                }
                private function submitClick():void
                {
                    if(gh.selectedIndex == 0)
                    {
                        if(name_client.text!="" && address_client.text!="" && phone_client.text!="")
                        {
    
                            temp_client = ({Name:name_client.text, Address:address_client.text,Phone_Number:phone_client.text});
                            dgItems_client.addItem(temp_client);
                            name_client.text="";
                            address_client.text="";
                            phone_client.text="";
                            clientClick();
                            errorClient.visible=false;
                        }
                        else
                        {
                            errorClient.visible=true;
                        }
                    }else
                    {
                        if(name_admin.text!="" && address_admin.text!="" && phone_admin.text!="")
                        {
                            temp_admin = ({Name:name_admin.text, Address:address_admin.text,Phone_Number:phone_admin.text});
                            dgItems_admin.addItem(temp_admin);
                            name_admin.text="";
                            address_admin.text="";
                            phone_admin.text="";
                            errorAdmin.visible=false;
                        }
                        else
                        {
                            errorAdmin.visible=true;
                        }
                    }
                }
    
                private function clientClick():void
                {
    
                    details.dataProvider=dgItems_client;
                    arrayName.headerText="Client_Name";
                }
                private function adminClick():void
                {
    
                    details.dataProvider=dgItems_admin;
                    arrayName.headerText="Admin_Name";
                }
    
                private function executeExport():void
                {
                    ExcelExporterUtil.dataGridExporter(this.details, "prueba_excel.xls");
                }
    
            ]]>
        </fx:Script>
        <mx:TabNavigator x="27" y="11" width="455" height="376" id="gh" change="tabChange()" backgroundColor="#A4B6E9">
            <s:NavigatorContent width="100%" height="100%" label="Client" id="clientTab">
                <s:Label x="10" y="30" width="52" height="25" text="Name:"/>
                <s:Label x="10" y="127" width="52" height="28" text="Address:"/>
                <s:TextInput id="name_client" x="69" y="18" width="188" height="37" restrict="a-zA-Z"/>
                <s:TextArea id="address_client" x="70" y="70" height="126"/>
                <s:Label x="10" y="230" width="84" height="32" text="Phone:"/>
                <s:TextInput id="phone_client" x="70" y="218" width="188" height="30" restrict="0-9" maxChars="10"/>
                <s:Button x="100" y="291" height="28" label="Submit"  click="submitClick()"/>           
                <s:Label id="errorClient" x="59" y="270" width="171" height="27" text="please fill the blank fields" color="red" visible="false"/>
            </s:NavigatorContent>
            <s:NavigatorContent width="100%" height="100%" label="Admin" id="adminTab" >
                <s:Label x="23" y="48" width="52" height="25" text="Name:"/>
                <s:Label x="26" y="148" width="52" height="28" text="Address:"/>
                <s:TextInput id="name_admin" x="105" y="33" width="188" height="37"/>
                <s:TextArea id="address_admin" x="105" y="93" height="126"/>
                <s:Label x="26" y="257" width="84" height="32" text="Phone:"/>
                <s:TextInput id="phone_admin" x="104" y="246" width="188" height="30" restrict="0-9" maxChars="10"/>
                <s:Button x="137" y="305" height="28" label="Submit" click="submitClick()"/>
                <s:Label id="errorAdmin" x="100" y="286" width="171" height="17" color="red" fontSize="14"
                         text="please fill the blank fields" visible="false"/>
                <s:Button x="335" y="60" height="34" label="Admin Details" click="adminClick()"/>
                <s:Button x="335" y="180" height="34" label="Client Details" click="clientClick()"/>
    
            </s:NavigatorContent>
        </mx:TabNavigator>
        <s:TitleWindow x="521" y="84" width="377" height="234">
            <mx:DataGrid x="0" y="0" width="375" height="163" borderVisible="true" id="details">
                <mx:columns>
                    <mx:DataGridColumn dataField="Name" id="arrayName"></mx:DataGridColumn>
                    <mx:DataGridColumn dataField="Address" headerText="Address"></mx:DataGridColumn>
                    <mx:DataGridColumn dataField="Phone_Number" headerText="Phone_Number"></mx:DataGridColumn>
                </mx:columns>
            </mx:DataGrid>
            <s:Button x="139" y="167" height="28" label="Export" click="executeExport()"/>
        </s:TitleWindow>
    </s:Application>
    

    ExcelExporterUtil.as公司

    package 
    {
        import com.as3xls.xls.ExcelFile;
        import com.as3xls.xls.Sheet;
    
        import flash.errors.IllegalOperationError;
        import flash.net.FileReference;
        import flash.utils.ByteArray;
    
        import mx.collections.ArrayCollection;
        import mx.collections.ICollectionView;
        import mx.collections.IViewCursor;
        import mx.collections.XMLListCollection;
        import mx.controls.DataGrid;
    
        public class ExcelExporterUtil
        {
            public function ExcelExporterUtil()
            {
                throw new IllegalOperationError("Class \"ExcelExporterUtil\" is static. You can't instance this");
            }
    
            static public function dataGridExporter(dg:DataGrid, defaultName:String):void
            {
                if (dg == null || dg.dataProvider == null || defaultName == null || defaultName == "")
                    return;
    
                var cols:Number = 0;
                var colsValues:Array = [];
                var cantCols:Number = dg.columnCount;
                var fieldT:String;
                var headerT:String;
    
                // armo el listado de headers y variables para cada columna
                for ( ; cols < cantCols; cols++)
                {
                    headerT = (dg.columns[cols] as Object).headerText
                    fieldT = (dg.columns[cols] as Object).dataField;
                    if ( fieldT == null || fieldT == "" || headerT == null || headerT == "")
                        continue; 
                    colsValues.push({
                        header:headerT,
                        value:fieldT
                    });
                }
    
                if ( colsValues.length == 0 )
                    return;
    
                ExcelExporterUtil.export(dg.dataProvider, colsValues, defaultName);
            }
    
            static public function chartExporter(chart:ByteArray, defautlName:String):void
            {
                if(chart)
                {
                    var sheet:Sheet = new Sheet();
                    sheet.resize(1, 1);
                    sheet.setCell(0, 0, "Chart Data");
    
                    sheet.setCell(0,0,chart);
    
                    var xls:ExcelFile = new ExcelFile();
                    xls.sheets.addItem(sheet);
                    var bytes:ByteArray = xls.saveToByteArray();
    
                    var fr:FileReference = new FileReference();
                    fr.save(bytes, defautlName);    
                }
            }
    
            static public function export(obj:Object, colsValues:Array, defautlName:String):void
            {
                var _dp:ICollectionView = ExcelExporterUtil.getDataProviderCollection(obj);
                if ( _dp == null )
                    return;
    
                var rows:Number = 0;
                var cols:Number = 0;
                var cantCols:Number = colsValues.length;
                var sheet:Sheet = new Sheet();
                sheet.resize(_dp.length, colsValues.length);
    
                for ( ; cols < cantCols; cols++)
                {
                    sheet.setCell(rows, cols, colsValues[cols].header);
                }
    
                cols = 0;
                rows++;
                var cursor:IViewCursor = _dp.createCursor();
                while ( !cursor.afterLast )
                {
                    for (cols = 0 ; cols < cantCols; cols++)
                    {
                        if ( (cursor.current as Object).hasOwnProperty(colsValues[cols].value) )
                            sheet.setCell(rows, cols, (cursor.current as Object));
                    }
    
                    rows++;
                    cursor.moveNext();
                }
    
                var xls:ExcelFile = new ExcelFile();
                xls.sheets.addItem(sheet);
                var bytes:ByteArray = xls.saveToByteArray();
    
                var fr:FileReference = new FileReference();
                fr.save(bytes, defautlName);
            }
    
            static private function getDataProviderCollection(obj:Object):ICollectionView
            {
                if ( (obj is Number && isNaN(obj as Number)) || (!(obj is Number) && obj == null))
                {
                    return null;
                }
                else if ( obj is ICollectionView )
                {
                    return obj as ICollectionView;
                }
                else if ( obj is Array )
                {
                    return new ArrayCollection(obj as Array);
                }
                else if ( obj is XMLList )
                {
                    return new XMLListCollection(obj as XMLList);
                }
                else if ( obj is XML )
                {
                    var col:XMLListCollection = new XMLListCollection();
                    col.addItem(obj);
                    return col;
                }
                else if ( obj is Object )
                {
                    return new ArrayCollection([obj]);
                }
                else
                {
                    return null;
                }
            }
        }
    }
    

    希望可以帮助你。。。。 注意:-我正在使用ExcelExporterUtil.as,来自其中一个帖子。。不是我创造的。。

    或者其他方式,可以参考下面的帖子:- http://cookbooks.adobe.com/post_Import_Export_data_in_out_of_a_Datagrid_in_Flex-17223.html