[Flex 3.0] 간편한 DataGrid Export Excel

FLEX/FLEX 2010. 7. 12. 21:48

아래 글은 DataGrid의 내용을 간단 하게 Excel로 나타내는것이다.

기존 Java Lib중 poi 라이브러리 보다는 가볍다.. 하지만 약간의 제한은 있는듯..

Flex 파일에 있는 Export Excel 버튼을 클릭하지 말고(클릭하면 보안 경고창 나타남)

See Example 클릭후 해보면 에러 없이 잘된다.

The following example shows how you can Export to Excel file from DataGrid in Flex 2.



See Example


Here are the instructions.

1: Create mxml file for the GUI with a data grid and export button.
MXML FILE [main.mxml]:
Code: Select all

<?xml version="1.0"?>
<!--
* RIASolve.
* Export data, delivered in the POST, to excel.
* @author Sobhan Dutta
-->


<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
   <mx:Script>
      <![CDATA[
         import com.riasolve.utils.DataGridDataExporter;
         private function exportExcel ():void
         {
            DataGridDataExporter.exportCSV(dg,"export.php"); // Change the file type based on the server you are using
            return;
         }
      ]]>
   </mx:Script>
    <mx:XMLList id="users">
        <user>
            <name>Christina Coenraets</name>
            <phone>555-219-2270</phone>
        </user>
        <user>
            <name>Joanne Wall</name>
            <phone>555-219-2012</phone>
        </user>       
    </mx:XMLList>
    <mx:Panel title="DataGrid Export Excel Example" height="100%" width="100%">       
        <mx:DataGrid id="dg" width="100%" height="100" rowCount="5" dataProvider="{users}">
            <mx:columns>
                <mx:DataGridColumn dataField="name" headerText="Name"/>
                <mx:DataGridColumn dataField="phone" headerText="Phone"/>
            </mx:columns>
        </mx:DataGrid>
       <mx:Button label="Export Excel" click="exportExcel ()"/>
    </mx:Panel>
</mx:Application>





2: Create a class file which does the export.
CLASS FILE [com.riasolve.utils.DataGridDataExporter]:
Code: Select all

/**
   * RIASolve.
   * Export data, delivered in the POST, to excel.
   * @author Sobhan Dutta
   */
package com.riasolve.utils
{
   import mx.controls.DataGrid;
   import mx.controls.dataGridClasses.DataGridColumn;
   import mx.collections.ArrayCollection;
   import mx.collections.XMLListCollection;
   import mx.collections.IList;
   import mx.collections.IViewCursor;
   import flash.net.URLVariables;
   import flash.net.URLRequest;
   import flash.net.URLRequestMethod;
   import flash.net.navigateToURL;
   
   public class DataGridDataExporter
   {

      public static function exportCSV(dg:DataGrid,
         jspFile:String,
         columnSeparator:String="\t",
         rowSeparator:String="\n"):void
      {
         var data:String = "";
         var columns:Array = dg.columns;
         var columnCount:int = columns.length;
         var column:DataGridColumn;
         var header:String = "";
         var headerGenerated:Boolean = false;
         var dataProvider:Object = dg.dataProvider;

         var rowCount:int = dataProvider.length;
         var dp:Object = null;

      
         var cursor:IViewCursor = dataProvider.createCursor ();
         var j:int = 0;
         
         header ='<table><thead>';
         data   = '<tr >';
         
         //loop through rows
         while (!cursor.afterLast)
         {
            var obj:Object = null;
            obj = cursor.current;
            
            if (headerGenerated)
               data += "<tr >";
               
            //loop through all columns for the row
            for(var k:int = 0; k < columnCount; k++)
            {
               column = columns[k];

               // Don't add if data is invisible
               if(!column.visible || column.dataField==null)
               {                  
                  continue;
               }
            
               data += "<td >"+ column.itemToLabel(obj)+ "</td >";

               //generate header of TSV, only if it's not genereted yet
               if (!headerGenerated)
               {
                  header += "<th >" + column.headerText + "</th >";
               }            
            }
            
            if (!headerGenerated){
               header += "</tr></thead><tbody>";
               headerGenerated = true;
            }

            data += "</tr >";
            j++;
            cursor.moveNext ();
         }
         
         data += "</tbody></table >"
         //set references to null:
         dataProvider = null;
         columns = null;
         column = null;         
         
         
         ////////////////////////////////////////////
         // Start opening into a new browser
         var variables:URLVariables = new URLVariables();
         variables.dg   = header + "\r\n" + data;
         
         //Setup a new request and make sure that we are
         //sending the data through a post
         var u:URLRequest = new URLRequest(jspFile);
         u.data = variables; //Pass the variables
         u.method = URLRequestMethod.POST; //Don't forget that we need to send as POST
         
         //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");

      }   
   }

}



3: Copy this PHP or JSP file in your webapp which will open the excel file.

Export file for PHP code [export.php]:
Code: Select all

<?php
/**
* Export data, delivered in the POST, to excel.
* @author Sobhan Dutta
*/
header('ETag: etagforie7download'); //IE7 requires this header
header('Content-type: application/octet_stream');
header('Content-disposition: attachment; filename="rapportage.xls"');

//Add html tags, so that excel can interpret it
echo "<html>
<body>
".stripslashes($_POST["dg"])."
</body>
</html>
";
?>



Export file for JSP code [export.jsp]:
Code: Select all

<%-- Set the content type header with the JSP directive --%>
<%@ page contentType="application/vnd.ms-excel" %>
                                                                                                                   
<%-- Set the content disposition header --%>
<% response.setHeader("Content-Disposition", "attachment; filename=\"odi.xls\""); %>

<%@page language="java" import="java.util.*" %>
<%
out.println(request.getParameter("dg"));
%>

출처 : http://forums.riasolve.com/viewtopic.php?f=2&t=2

: