Flex EXCEL导出

flex端:

     <?xml version = "1.0" encoding = "utf-8"?>
<mx:Application xmlns:mx = "http://www.adobe.com/2006/mxml"
                layout = "absolute">

    <mx:Script>
        <![CDATA[
            import flash.errors.*;
            import flash.events.*;
            import flash.external.*;
            import flash.net.URLRequest;
            import flash.net.URLVariables;
            import mx.collections.ArrayCollection;

            [Bindable]
            private var datalist:ArrayCollection =
                            new ArrayCollection([{ 姓名: "张三", 性别: "男", 年龄: "23", 生日: "1984-01-12" },
                                                 { 姓名: "李四", 性别: "男", 年龄: "27", 生日: "1983-11-2" }]);

            /**
             * Convert the datagrid to a html table
             * Styling etc. can be done externally
             *
             * @param: dg Datagrid Contains the datagrid that needs to be converted
             * @returns: String
             */
            private function convertDGToHTMLTable(dg:DataGrid):String
            {
                //Set default values
                var font:String = dg.getStyle('fontFamily');
                var size:String = dg.getStyle('fontSize');
                var str:String = '';
                var colors:String = '';
                var style:String = 'style="font-family:' + font + ';font-size:' + size + 'pt;"';
                var hcolor:Array;

                //Retrieve the headercolor
                if (dg.getStyle("headerColor") != undefined)
                {
                    hcolor = [ dg.getStyle("headerColor")];
                }
                else
                {
                    hcolor = dg.getStyle("headerColors");
                }

                //Set the htmltabel based upon knowlegde from the datagrid
                //解决乱码<head><meta http-equiv="Content-Type" content="text/htm; charset=utf-8"></head>
                str +=
                                '<head><meta http-equiv="Content-Type" content="text/htm; charset=utf-8"></head><table width="' + dg.width + '" border="1"><thead><tr width="' + dg.width + '" style="background-color:#' + Number((hcolor[0])).toString(16) + '">';

                //Set the tableheader data (retrieves information from the datagrid header    
                for (var i:int = 0; i < dg.columns.length; i++)
                {
                    colors = dg.getStyle("themeColor");

                    if (dg.columns[i].headerText != undefined)
                    {
                        str += "<th " + style + ">" + dg.columns[i].headerText + "</th>";
                    }
                    else
                    {
                        str += "<th " + style + ">" + dg.columns[i].dataField + "</th>";
                    }
                }
                str += "</tr></thead><tbody>";
                colors = dg.getStyle("alternatingRowColors");

                //Loop through the records in the dataprovider and
                //insert the column information into the table
                for (var j:int = 0; j < dg.dataProvider.length; j++)
                {
                    str += "<tr width=/"" + Math.ceil(dg.width) + "/">";

                    for (var k:int = 0; k < dg.columns.length; k++)
                    {

                        //Do we still have a valid item?      
                        if (dg.dataProvider.getItemAt(j) != undefined &&
                                        dg.dataProvider.getItemAt(j) != null)
                        {

                            //Check to see if the user specified a labelfunction which we must
                            //use instead of the dataField
                            if (dg.columns[k].labelFunction != undefined)
                            {
                                str +=
                                                "<td width=/"" + Math.ceil(dg.columns[k].width) + "/" " + style + ">" + dg.columns[k].labelFunction(dg.dataProvider.getItemAt(j),
                                                                                                                                                                              dg.columns[k].dataField) + "</td>";

                            }
                            else
                            {
                                //Our dataprovider contains the real data
                                //We need the column information (dataField)
                                //to specify which key to use.
                                str +=
                                                "<td width=/"" + Math.ceil(dg.columns[k].width) + "/" " + style + ">" + dg.dataProvider.getItemAt(j)[dg.columns[k].dataField] + "</td>";
                            }
                        }
                    }
                    str += "</tr>";
                }
                str += "</tbody></table>";

                return str;
            }

            private function loadDGInExcel(dg:DataGrid, url:String):void
            {

                //Pass the htmltable in a variable so that it can be delivered
                //to the backend script
                var variables:URLVariables = new URLVariables();
                variables.htmltable = convertDGToHTMLTable(dg);

                //Setup a new request and make sure that we are
                //sending the data through a post
                var u:URLRequest = new URLRequest(url);
                u.data = variables; //Pass the variables
                u.method = URLRequestMethod.POST; //Don't forget that we need to send as POST

                //Navigate to the script
                //We can use _self here, since the script will through a filedownload header
                //which results in offering a download to the user (and still remaining in you Flex app.)
                navigateToURL(u, "_self");
            }
        ]]>
    </mx:Script>

    <mx:DataGrid id = "statdatagrid"
                 dataProvider = "{datalist}"
                 width = "460"
                 x = "107"
                 y = "100">
    </mx:DataGrid>

    <mx:Button label = "导出Excel"
               x = "485"
               y = "70"
               click = "loadDGInExcel(statdatagrid,'excelexport.jsp');"/>
</mx:Application>

 

后台jsp:

        <%@ page language="java"%>
       <%@ page contentType="application/vnd.ms-excel;charset=UTF-8"
                                                                        pageEncoding="UTF-8"%>
       <%
         request.setCharacterEncoding("UTF-8");
         response.setHeader("Content-disposition","attachment; filename=test.xls");
         String str = request.getParameter("htmltable");
         out.print(str);
     %>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
<?xml version="1.0" encoding="utf-8"?> <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ import mx.controls.CheckBox; import mx.controls.Alert; import com.as3xls.xls.ExcelFile; import com.as3xls.xls.Sheet; import flash.filesystem.*; [Bindable] private var dp:Array = [ {idx:1, names: "test1", sex: "b" }, {idx:2, names: "test2", sex: "g" } ]; public function doSelect(o:Object):void { Alert.show("行的数据分别是:"+o.idx+"/"+o.names+"/"+o.sex); } private var sheet:Sheet; private function onCreate():void { var excelFile:ExcelFile = new ExcelFile(); sheet = new Sheet(); sheet.resize(10, 10); sheet.setCell(0, 0, "Today's date:"); sheet.setCell(0, 1, new Date()); excelFile.sheets.addItem(sheet); var mbytes:ByteArray = excelFile.saveToByteArray(); var stream:FileStream = new FileStream(); var docsDir:File = File.documentsDirectory.resolvePath("abc.xls"); // 定死文件名 try { docsDir.browseForSave("Save As"); docsDir.addEventListener(Event.SELECT, saveData); } catch (error:Error) { trace("Failed:", error.message) } function saveData(event:Event):void { var newFile:File = event.target as File; if (!newFile.exists) { var stream:FileStream = new FileStream(); stream.open(newFile, FileMode.WRITE); stream.writeBytes(mbytes); // 写文件流 stream.close(); } } } ]]> </mx:Script> <mx:Panel> <mx:Button label="导出" click="onCreate()"/> <mx:DataGrid id="dg1" dataProvider ="{dp}"> <mx:columns> <mx:DataGridColumn width="20" headerText="" > <mx:itemRenderer> <mx:Component> <mx:CheckBox change=" {outerDocument.doSelect(data as Object)} " /> </mx:Component> </mx:itemRenderer> </mx:DataGridColumn> <mx:DataGridColumn headerText="names" dataField="names" width="200" /> <mx:DataGridColumn headerText="sex" dataField="sex" width="300" /> </mx:columns> </mx:DataGrid> </mx:Panel> </mx:WindowedApplication>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值