flex dg转存excel的几种方法。

来源:互联网 发布:heattech 知乎 编辑:程序博客网 时间:2024/05/18 22:41

====================================================

方法一:我这里使用的是tomcat,可以使用的后台jsp或者asp,我用了jsp。这种方法使用了后台的jsp来

/*****************************
    * 函数名:dgToXls()
    * 功能:将dg的表信息转为html格式的字符串
    * 数据库:无
    * 参数:无
    * 返回值:str
    * 调用函数:
    * 修改记录:
    * ***************************/
   public function dgToXls():String
   {
    /** 在导出数据的时候有可能出现单元格数据长度过长而导致Excel在显示时  
     *  出现科学计数法或者#特殊符号,在此设置单元格宽度比例WIDTHSCALE,在  
     *  代码中每个单元格的宽度扩展适当的比例值WIDTHSCALE。  
     */  
     var WIDTHSCALE:Number=2.0;
     /**  
      * 将DataGrid转换为htmltable   
      * @param: dg需要转换成htmltable的DataGrid  
      * @return: String  
      */ 
     var font:String = netInspectlogDataGrid.getStyle('fontFamily');  
     var size:String = netInspectlogDataGrid.getStyle('fontSize');  
     var str:String = '';  
     var colors:String = '';  
     var style:String = 'style="font-family:'+font+';font-size:'+size+'pt;"';                  
     var headColor:Array=new Array;  
     //检索DataGrid的 headercolor  
     if(netInspectlogDataGrid.getStyle("headerColor") != undefined)
     {  
      headColor =[ netInspectlogDataGrid.getStyle("headerColor")];  
     }
     else
     {  
      headColor =[ netInspectlogDataGrid.getStyle("headerColors")];  
     } 
     str += '<table width="'+netInspectlogDataGrid.width+'" border="1"><thead><tr width="'+netInspectlogDataGrid.width+'" style="background-color:#' +Number((headColor[0])).toString(16)+'">';
     //设置tableheader数据(从datagrid的header检索headerText信息) 
     for(var i:int = 0;i<1/* netInspectlogDataGrid.columns.length */;i++)
     {  
      colors = netInspectlogDataGrid.getStyle("themeColor");  
     
      if(netInspectlogDataGrid.columns[i].headerText != undefined)
      {  
       str+="<th "+style+">"+netInspectlogDataGrid.columns[i].headerText+"</th>";  
      }
      else
      {  
       str+= "<th "+style+">"+netInspectlogDataGrid.columns[i].dataField+"</th>";  
      }  
     }   
     str += "</tr></thead><tbody>";  
     colors = netInspectlogDataGrid.getStyle("alternatingRowColors");  
     for(var j:int =0;j< (netInspectLog.length)  ;j++)
     {                   
      str +="<tr width=\""+Math.ceil(netInspectlogDataGrid.width)+"\">";  
     
      for(var k:int=0; k < 1/* netInspectlogDataGrid.columns.length */; k++)
      {         
       if(netInspectlogDataGrid.dataProvider.getItemAt(j) != undefined && netInspectlogDataGrid.dataProvider.getItemAt(j) != null)
       { 
        if(netInspectlogDataGrid.columns[k].labelFunction != undefined)
        {  
         str += "<td width=\""+Math.ceil(netInspectlogDataGrid.columns[k] .width*WIDTHSCALE)+"\" "+style+">"+netInspectlogDataGrid.columns[k].labelFunction(netInspectlogDataGrid.dataProvider.getItemAt(j),netInspectlogDataGrid.columns[k].dataField)+"</td>";
        }
        else
        {  
         str += "<td width=\""+Math.ceil(netInspectlogDataGrid.columns[k].width*WIDTHSCALE)+"\" "+style+">"+netInspectlogDataGrid.dataProvider.getItemAt(j)[(netInspectlogDataGrid.columns[k] as DataGridColumn).dataField]+"</td>";  
        }  
       }  
      }  
      str += "</tr>";  
     }  
     str +="</tbody></table>";
     return str;
   }
   
   /*****************************
    * 函数名:loadDGInExcel()
    * 功能:输出excel的jsp方法,将dgToXls()方法返回的str转存到excel
    * 数据库:无
    * 参数:无
    * 返回值:
    * 调用函数:dgToXls()
    * 修改记录:
    * ***************************/
   private function loadDGInExcel(surl:String):void
   {
    /**  
    * 将制定的DataGrid加载到Excel文件,此方法传入一个htmltable字符串参数到后台Script脚本,然后浏览器给用户提供一个Excel下载  
    * @author Chenwenfeng  
    * @params dg 需要导入的数据源DataGrid  
    * @params url excel文件下载路径  
    */  
    var variables:URLVariables = new URLVariables();
    variables.htmltable = dgToXls();
    var u:URLRequest = new URLRequest(surl);
    u.data = variables;
    u.method = URLRequestMethod.POST;
    navigateToURL(u,"_self");
   }

菜单上选择输出的时候:

switch (data){

*

中间是其他的一些菜单,这里就略掉了!

*

case "outPut":
          loadDGInExcel("http://localhost:8080/sampleone/ExportToXls.jsp"); 
      break;

default:

}

最重要的就是:ExportToXls.jsp文件了,要放到tomcat的Tomcat 6.0\webapps\"你的工程下",就可以了。

ExportToXls.jsp内部的代码:

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

 ********************

方法一有一些缺点:当你的datagrid数据量很大的时候,比如说10*10000多的数据,那么就会出现在方法:public function dgToXls():String{return str}时候str会内存溢出!

如果数据量少的话,可以使用。没有问题。

 

==========================================

方法二:这种方法不涉及到后台的调用了,只是用前台来处理就可以实现。

* 输出xls新方法
  ========================================= 
  ========================================= 
  */
   import mx.controls.dataGridClasses.DataGridColumn;
   import com.as3xls.xls.Cell;
   import mx.collections.ArrayCollection;
   import com.as3xls.xls.Sheet;
   import com.as3xls.xls.ExcelFile;
   
   private var fileReference:FileReference;
   private var xls:Class;
   private var sheet:Sheet;
   
   [Bindable]
   private var fields:Array = new Array();
   
   private function fileReference_Cancel(event:Event):void
   {
    fileReference = null;
   }
   
   private function exportToExcel():void
   {
    sheet = new Sheet();
    var dataProviderCollection:ArrayCollection =netInspectLog;
    var rowCount:int = dataProviderCollection.length;
    sheet.resize(rowCount + 1,netInspectlogDataGrid.columnCount);
    var columns:Array = netInspectlogDataGrid.columns;
    var i:int = 0;
    for each (var field:DataGridColumn in columns){
     fields.push(field.dataField.toString());/*  .toString() */
     sheet.setCell(0,i,field.dataField.toString());
     i++;
    }
    
    for(var r:int=0; r < rowCount; r++)
    {
     var record:Object = dataProviderCollection.getItemAt(r);
     /*insert record starting from row no 2 else
     headers will be overwritten*/
     insertRecordInSheet(r+1,sheet,record);
    }
    var xls:ExcelFile = new ExcelFile();
    xls.sheets.addItem(sheet);
    
    var bytes: ByteArray = xls.saveToByteArray();
    var fr:FileReference = new FileReference();
    fr.save(bytes,"SampleExport.xls"); 
   }
   private function insertRecordInSheet(row:int,shet:Sheet,recod:Object):void
   {
    var colCount:int = netInspectlogDataGrid.columnCount;
    for(var c:int=0; c < colCount; c++)
    {
     var i:int = 0;
     for each(var field:String in fields){
      for each (var value:String in recod){
       if (recod[field]==null)
        recod[field]="";
       if (recod[field].toString() == value)
        shet.setCell(row,i,value);
      }
      i++;
     }
    }
   }
  注意的是:一定要把as3xls-1.0.1.swc包导入。它可以用来建立xls文件,并写入信息。as3xls-1.0.swc也可以实现建立xls文件,并写入信息,但是它输出的中文是乱码的,而as3xls-1.0.1.swc可以处理中文乱码。这样就可以实现了dg->xls并且无乱码转存了。

===========================================

方法三:大家可以看一下一位大侠写的帖子,我本人没有怎么仔细看,不过应该是非常简单的。大家看一下这位大侠的博客网址吧:http://jhaij.iteye.com/blog/792786