Flex导出Excel

Flex前端+Java后台,要将Flex界面中AdvancedDataGrid的数据导出成Excel文件。有2种方法:

1.直接在前台导出。
    使用开源项目as3xls,下载个解决了中文乱码的as3xlsUTF8.swc包,加到Flex工程的引用库中。
    AS代码,点击“导出Excel”按钮后的函数:

Java代码 复制代码  收藏代码
  1. var sheet:Sheet = new Sheet();   
  2. private function export2ExcelHandel(e:MouseEvent):void  
  3. {   
  4.     //在前台生成Excel   
  5.     var excelFile:ExcelFile=new ExcelFile();   
  6.     var arr:ArrayCollection=myTable.dataProvider as ArrayCollection;   
  7.     for(var i:int=0; i<arr.length; i++)   
  8.     {   
  9.         var obj:Object=arr[i];   
  10.         var j:int=0;   
  11.         for(var key:String in obj)   
  12.         {   
  13.             excelFile.sheets.addItem(generateSheet(0,j,key));      
  14.             excelFile.sheets.addItem(generateSheet(i,j,obj[key]));   
  15.             j++;   
  16.         }   
  17.     }          
  18.     var mbytes:ByteArray=excelFile.saveToByteArray();   
  19.     var file:FileReference=new FileReference();   
  20.     file.save(mbytes,"测试文件.xls");    
  21. }   
  22.                
  23. function generateSheet(i:int,j:int,o:Object):Sheet{   
  24.     if(!sheet){       
  25.         sheet = new Sheet();       
  26.         sheet.resize(10,10);       
  27.     }       
  28.     sheet.setCell(i, j, String(o));       
  29.     return sheet;       
  30. }      
var sheet:Sheet = new Sheet();
private function export2ExcelHandel(e:MouseEvent):void
{
    //在前台生成Excel
    var excelFile:ExcelFile=new ExcelFile();
    var arr:ArrayCollection=myTable.dataProvider as ArrayCollection;
    for(var i:int=0; i<arr.length; i++)
    {
        var obj:Object=arr[i];
        var j:int=0;
        for(var key:String in obj)
        {
            excelFile.sheets.addItem(generateSheet(0,j,key));	
            excelFile.sheets.addItem(generateSheet(i,j,obj[key]));
            j++;
        }
    }       
    var mbytes:ByteArray=excelFile.saveToByteArray();
    var file:FileReference=new FileReference();
    file.save(mbytes,"测试文件.xls"); 
}
			
function generateSheet(i:int,j:int,o:Object):Sheet{
    if(!sheet){    
        sheet = new Sheet();    
        sheet.resize(10,10);    
    }    
    sheet.setCell(i, j, String(o));    
    return sheet;    
}    


FileReference的save方法在Flash10才支持,
在Flex工程上右键,属性,Flex Conpiler中把Require Flash Player version:填为10.0.0;在Flex Build Path中加入playerglobal.swc
,路径为…\sdks\3.2.0\frameworks\libs\player\10\playerglobal.swc

2.通过调JSP或Servlet导出。
AS代码:

Java代码 复制代码  收藏代码
  1. public static function ToExcel(dg:AdvancedDataGrid,name:String)   
  2. {   
  3.     //调用JSP   
  4.     var url:String="http://localhost:8080/XXX/Export/ExcelExport.jsp";   
  5.     var variables:URLVariables = new URLVariables();    
  6.     variables.htmltable = convertDGToHTMLTable(dg);   
  7.     var u:URLRequest = new URLRequest(url);   
  8.     u.data = variables;   
  9.     u.method = URLRequestMethod.POST;   
  10.     navigateToURL(u,"_self");    
  11. }   
  12.   
  13. private static function convertDGToHTMLTable(dg:AdvancedDataGrid):String {   
  14.     //Set default values   
  15.     var font:String = dg.getStyle('fontFamily');   
  16.     var size:String = dg.getStyle('fontSize');   
  17.     var str:String = '';   
  18.     var colors:String = '';   
  19.     var style:String = 'style="font-family:'+font+';font-size:'+size+'pt;"';                   
  20.     var hcolor:Array;   
  21.           
  22.     //Retrieve the headercolor   
  23.     if(dg.getStyle("headerColor") != undefined) {   
  24.         hcolor = [dg.getStyle("headerColor")];   
  25.     } else {   
  26.         hcolor = dg.getStyle("headerColors");   
  27.     }                   
  28.           
  29.     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)+'">';   
  30.     for(var i:int = 0;i<dg.columns.length;i++) {   
  31.         colors = dg.getStyle("themeColor");               
  32.         if(dg.columns[i].headerText != undefined) {   
  33.             str+="<th "+style+">"+dg.columns[i].headerText+"</th>";                     
  34.         } else {   
  35.             str+= "<th "+style+">"+dg.columns[i].dataField+"</th>";   
  36.         }   
  37.     }   
  38.     str += "</tr></thead><tbody>";   
  39.     colors = dg.getStyle("alternatingRowColors");   
  40.     for(var j:int =0;j<dg.dataProvider.length;j++)    
  41.     {                       
  42.         str+="<tr width=\""+Math.ceil(dg.width)+"\">";   
  43.                   
  44.         for(var k:int=0; k < dg.columns.length; k++) {   
  45.             if(dg.dataProvider.getItemAt(j) != undefined && dg.dataProvider.getItemAt(j) != null) {                 
  46.                 if(dg.columns[k].labelFunction != undefined) {   
  47.                     str += "<td width=\""+Math.ceil(dg.columns[k].width)+"\" "+style+">"+dg.columns[k].labelFunction(dg.dataProvider.getItemAt(j),dg.columns[k].dataField)+"</td>";   
  48.                 }    
  49.                 else {   
  50.                     str += "<td width=\""+Math.ceil(dg.columns[k].width)+"\" "+style+">"+dg.dataProvider.getItemAt(j)[dg.columns[k].dataField]+"</td>";   
  51.                 }   
  52.             }   
  53.         }   
  54.         str += "</tr>";   
  55.     }   
  56.     str+="</tbody></table>";   
  57.     return str;   
  58. }  
public static function ToExcel(dg:AdvancedDataGrid,name:String)
{
    //调用JSP
    var url:String="http://localhost:8080/XXX/Export/ExcelExport.jsp";
    var variables:URLVariables = new URLVariables(); 
    variables.htmltable = convertDGToHTMLTable(dg);
    var u:URLRequest = new URLRequest(url);
    u.data = variables;
    u.method = URLRequestMethod.POST;
    navigateToURL(u,"_self"); 
}

private static function convertDGToHTMLTable(dg:AdvancedDataGrid):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");
    }                
	   
    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)+'">';
    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");
    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++) {
            if(dg.dataProvider.getItemAt(j) != undefined && dg.dataProvider.getItemAt(j) != null) {              
                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 {
                    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;
}



ExcelExport.jsp放在后台XXX工程的WebRoot下的Export文件夹中。
ExcelExport.jsp:

Java代码 复制代码  收藏代码
  1. <%@ page language="java"%>   
  2. <%@ page contentType="application/msexcel;charset=UTF-8"  
  3.     pageEncoding="UTF-8"%>   
  4. <%   
  5. request.setCharacterEncoding("UTF-8");   
  6. //String instr=request.getParameter("filename");   
  7. response.setHeader("Content-disposition","attachment; filename=excel.xls");   
  8. response.setCharacterEncoding("UTF-8");   
  9. String str = request.getParameter("htmltable");   
  10. out.print(str);   
  11. %>  

你可能感兴趣的:(导出Excel)