DataGridDataExporter: Export DataGrid data as CSV

A friend of mine, who is new to Adobe Flex, asked how can Datagrid-data be exported as CSV. I wrote a simple class, with one static-method, to do that. This is very basic implementation of CSV format.

Check out the example or download the code (with example).

DataGridDataExporter.as:

/**
_________________________________________________________________________________________________________________
DataGridDataExporter is a util-class to export DataGrid's data into different format.
@class DataGridDataExporter (public)
@author Abdul Qabiz (mail at abdulqabiz dot com)
@version 0.01 (2/8/2007)
@availability 9.0+
@usage<code>DataGridDataExporter.<staticMethod> (dataGridReference)</code>
@example
<code>
var csvData:String = DataGridDataExporter.exportCSV (dg);
</code>
__________________________________________________________________________________________________________________
*/
package com.abdulqabiz.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 mx.collections.CursorBookmark;
public class DataGridDataExporter
{
public static function exportCSV(dg:DataGrid, csvSeparator:String="\t", lineSeparator:String="\n"):String
{
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;
//loop through rows
			while (!cursor.afterLast)
{
var obj:Object = null;
obj = cursor.current;
//loop through all columns for the row
				for(var k:int = 0; k < columnCount; k++)
{
column = columns[k];
//Exclude column data which is invisible (hidden)
					if(!column.visible)
{
continue;
}
data += "\""+ column.itemToLabel(obj)+ "\"";
if(k < (columnCount -1))
{
data += csvSeparator;
}
//generate header of CSV, only if it's not genereted yet
					if (!headerGenerated)
{
header += "\"" + column.headerText + "\"";
if (k < columnCount - 1)
{
header += csvSeparator;
}
}
}
headerGenerated = true;
if (j < (rowCount - 1))
{
data += lineSeparator;
}
j++;
cursor.moveNext ();
}
//set references to null:
			dataProvider = null;
columns = null;
column = null;
return (header + "\r\n" + data);
}
}
}

DataGridCSVExportExample.mxml:-

<?xml version="1.0"?>
<!-- DataGrid control example. -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import com.abdulqabiz.utils.DataGridDataExporter;
private function exportCSV ():void
{
console.text = DataGridDataExporter.exportCSV (dg);
}
]]>
</mx:Script>
<mx:XMLList id="employees">
<employee>
<name>Christina Coenraets</name>
<phone>555-219-2270</phone>
<email>[email protected]</email>
<active>true</active>
</employee>
<employee>
<name>Joanne Wall</name>
<phone>555-219-2012</phone>
<email>[email protected]</email>
<active>true</active>
</employee>
<employee>
<name>Maurice Smith</name>
<phone>555-219-2012</phone>
<email>[email protected]</email>
<active>false</active>
</employee>
<employee>
<name>Mary Jones</name>
<phone>555-219-2000</phone>
<email>[email protected]</email>
<active>true</active>
</employee>
</mx:XMLList>
<mx:Panel title="DataGrid Control Example" height="100%" width="100%"
paddingTop="10" paddingLeft="10" paddingRight="10">
<mx:Label width="100%" color="blue"
text="Select a row in the DataGrid control."/>
<mx:DataGrid id="dg" width="100%" height="100%" rowCount="5" dataProvider="{employees}">
<mx:columns>
<mx:DataGridColumn dataField="name" headerText="Name"/>
<mx:DataGridColumn dataField="phone" headerText="Phone"/>
<mx:DataGridColumn dataField="email" headerText="Email"/>
</mx:columns>
</mx:DataGrid>
<mx:Button label="Export CSV" click="exportCSV ()"/>
<mx:TextArea id="console" width="100%" height="100%" />
</mx:Panel>
</mx:Application>

Technorati tags: , , , ,

  • This can be quite handy .. one use I can think of off the top of my head is export as excel … if you save csv content as a file with .xls extension and then open the file in excel .. excel will read it properly.
    Thanks!

  • Megharaja

    Instead of storing into textarea i want to store into csv file .
    can you tel me how to do this ?
    Thanks,
    Megharaja S.H.

  • @Megharaja: If you are using AIR, you can save data in a file using File API. If your application runs in browser, you need to use FileReference API to send data to server-side-script, which would return (or just echo) the data back to client and client would be prompted to save the file…
    Following is simple Flex code, you can write php or any other server-side support your own. I am posting here a Java-Servlet code, which i wrote to help someone else. Basically, server-side script takes data over HTTP/POST and returns the data with right MIME-TYPE…

    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script>
    <![CDATA[
    import com.abdulqabiz.utils.DataGridDataExporter;
    import flash.net.FileReference;
    import flash.net.URLRequest;
    import flash.net.URLVariables;
    import flash.net.URLRequestMethod;
    private static const CSV_DOWNLOAD_END_POINT:String = "http://localhost/getcsv";
    private var downloadFileRef:FileReference = null;
    private function exportCSV ():void
    {
    var csvData:String = DataGridDataExporter.exportCSV (dg);
    console.text = csvData;
    if (csvData.length > 0)
    {
    downloadCSV (csvData);
    }
    }
    private function downloadCSV (csvData:String):void
    {
    if (!downloadFileRef)
    {
    downloadFileRef = new FileReference ();
    }
    var request:URLRequest = new URLRequest ();
    request.url = CSV_DOWNLOAD_END_POINT;
    request.method = URLRequestMethod.POST;
    request.data = new URLVariables ("csvdata=" + csvData);
    downloadFileRef.download (request, "file.csv");
    }
    ]]>
    </mx:Script>
    <mx:XMLList id="employees">
    <employee>
    <name>Christina Coenraets</name>
    <phone>555-219-2270</phone>
    <email>[email protected]</email>
    <active>true</active>
    </employee>
    <employee>
    <name>Joanne Wall</name>
    <phone>555-219-2012</phone>
    <email>[email protected]</email>
    <active>true</active>
    </employee>
    <employee>
    <name>Maurice Smith</name>
    <phone>555-219-2012</phone>            <email>[email protected]</email>
    <active>false</active>
    </employee>
    <employee>
    <name>Mary Jones</name>
    <phone>555-219-2000</phone>            <email>[email protected]</email>
    <active>true</active>
    </employee>
    </mx:XMLList>
    <mx:Panel title="DataGrid Control Example" height="100%" width="100%"
    paddingTop="10" paddingLeft="10" paddingRight="10">
    <mx:Label width="100%" color="blue"
    text="Select a row in the DataGrid control."/>
    <mx:DataGrid id="dg" width="100%" height="100%" rowCount="5" dataProvider="{employees}">
    <mx:columns>
    <mx:DataGridColumn dataField="name" headerText="Name"/>
    <mx:DataGridColumn dataField="phone" headerText="Phone"/>
    <mx:DataGridColumn dataField="email" headerText="Email"/>
    </mx:columns>
    </mx:DataGrid>
    <mx:Button label="Export CSV" click="exportCSV ()"/>
    <mx:TextArea id="console" width="100%" height="100%" />
    </mx:Panel>
    </mx:Application>
    
    /**
    *
    */
    package com.abdulqabiz.util
    import java.io.IOException;
    import java.net.URLEncoder;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    /**
    * This servlet echos the data as CSV
    * 

    *

    * * @author Abdul Qabiz */ public class GetCSV extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setHeader("Content-Type", "text/csv"); if (req.getParameter("csvdata") != null) { res.getOutputStream().print(req.getParameter("csvdata")); } } }

    • mohd

      Great work Abdul ……….just what I was looking for but it really took time for me to come to this page on google………….Thanks a lot

  • Jessica

    Thank you so much for the code. I looked all over the place on the Internet and finally found this blog entry. It helped me tremendously. Thanks again.

  • Xinen

    Thank you very much.But I also have some problems.What can I do then?
    First,copy the data to clipboard. Then copy the data to EXCEL again.
    This problems is Complex ,I think.
    So I wish somebody can help me.

  • saurabh narula

    if we will try to write this csv string in excel file and if any of the data fields contains “?” character..the approach fails…the data after the character ? is not written to the excel file.

  • Prasanth

    Thanks for the code .But to run the servlet you need to run LDS .Is there a way to acheive save operation without LDS

  • @Prasanth: That servlet is just for example, you can surely do the same using PHP/ASP or any server-side script…
    It’s probably lot simple in PHP, you have to just echo the content, received with GET/POST, to client and also set the HTTP headers in response…
    This should work (just wrote not tested):-
    savecsv.php:-

    <?php
    header('Content-type: text/csv');
    $csvData = ($_POST['csvdata']) ? $_POST['csvdata'] : $_GET['csvdata'];
    echo  $csvData;
    ?>

    You can send the data either via query-string (GET) or POST. I suggest, you use HTTP Post to send csvdata. I have not put the checks in there, you can always modify it to handle errors etc..
    In above Flex code, change the value of constant “CSV_DOWNLOAD_END_POINT” to the URL of this php..
    Hope that helps..
    -abdul

  • uday

    its a good article. it helps me a lot.
    i have some little problem while running this code.
    iam using lcd services with java backend.
    when i open the downloaded csv file, content of the single row comes in single cell(excel sheet box), its not differentiate the cell wise like in my file
    ‘”Uyda “”assets/icons/phone_sound.png”” “” 4985623658″” “”Tue Jan 8 19:44:00 GMT 0530 2008″” “”0″” “”98.48898″” “”13.28463″” “”0″” “”123″””

    but it must be differentiate by single cell, Could u please help me out in this

  • Prasanth

    Hey
    Instead of copying data from the datagrid is it possible to convert the XML which is the input to CSV and download it …

  • tugadot

    Hello,
    How i can implement the same trick to send a dataProvider ( all datagrid information) to php? To use this information as $message to send email?
    Can you help me?
    Thks

  • Paul Chavez

    Hi Abdul,
    Thanks a lot, it is what I was looking for export my reports to excel.
    I have a lot of reports, In my reports I have labels showing the totals for the columns, and I needed to export the totals too.
    Based in your code I created the function exportArrayCSV to send the totals as array, export to CSV and join to the datagrid exportCSV.
    Could help somebody that have reports with totals.

    public function exportArrayCSV (array:Array, csvSeparator:String="\t", lineSeparator:String="\n"):String
    {
    var data:String = "";
    //loop through all columns for the row
    for(var i:int = 0; i
    {
    data += "\""+ array[i] + "\"";
    if(i 
  • Paul Chavez
    public function exportArrayCSV (array:Array, csvSeparator:String="\t", lineSeparator:String="\n"):String
    {
    var data:String = "";
    //loop through all columns for the row
    for(var i:int = 0; i
    {
    data += "\""+ array[i] + "\"";
    if(i < (array.length -1))
    {
    data += csvSeparator;
    }
    }
    return ("\r\n" + data);
    }
    //Sample how to join the datagrid exportCSV with the Totals exportCSV and assign to Clipboard.
    private function exportCSV (dg:DataGrid):void
    {
    var strCSV : String;
    var array : Array = new Array("Total","test");
    strCSV = DataGridDataExporter.exportCSV(dg);
    strCSV += exportArrayCSV(array);
    System.setClipboard( strCSV )
    }
    
  • susan

    Why the client side csv data sending to server and then storing on client side. is there any direct approach without using server side script

  • sindhu

    Hi!
    I wanna know the Flex code to open a FILE OPEN dialog box when i click the Browse buttton designed in my Fornt end..

  • Muralidharan

    Hai Abdul,
    How can i export images (jpg,png) using Flex with java servlet?
    Thanks.

  • Sheetal

    Hi
    I have a xml file where im storing the book details like title,author etc.
    In my application I have a option to add book details which should update the xml file.How can i get this done?
    Thanx
    Sheetal

  • Mohammad

    Hey
    I’m using Flex 3 and Developing a web application. and this application deals with oracle database. I want to generate report from the databse, is there anyway to expert a pdf through flex.
    Thanks in advance

    • mohd

      Salam,

      look for alive pdf with flex …….you can do with it

  • Prajilal

    Can anyone give me the ASP.Net code for export csv data to excel?

  • Prajilal

    Can Any one help me to export csv data to excel using asp.net?
    Regards,
    Praji

  • Rick

    This code errors out on 1120: Access of undefined property DataGridDataExporter. How is every onelse getting it to work?

  • Bart

    How about server side code for ASP.NET? I’ve looked everywhere. I tried to write my own but the data comes back all messed up filled with Percent signs for every space and tab in my datagrid.
    %22 for
    %20 for
    C for ,
    For example this is what my ASP.NET C# code spits back:
    Roof%22%09%2270%2C688%22%09%22SQ%20FT
    It should read:
    “Roof” “70,688” “SQ FT”
    Here’s my code maybe someone can tell me where I’m wrong?
    using System;
    using System.Web;
    public class Handler : IHttpHandler
    {
    public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = “text/plain”;
    long streamLength = context.Request.InputStream.Length;
    int myStreamLength = (int)streamLength;
    byte[] bytes = new byte[myStreamLength];
    context.Request.ContentType = “text/plain”;
    context.Request.InputStream.Read(bytes,0,myStreamLength);
    context.Response.OutputStream.Write(bytes,0,myStreamLength);
    }
    public bool IsReusable {
    get {
    return false;
    }
    }
    }

  • Manu

    Could you provide the jsp file in place of the php file, if one wants to use java?
    Thanks in advance.

  • Anil

    here is the ASP.NET/c# code to add the appropriate MIME type
    public partial class Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    string csvData = Request.Params[“csvdata”];
    if (!string.IsNullOrEmpty(csvData))
    {
    Response.Clear();
    Response.Charset = “”;
    Response.ContentType = “text/csv”;
    Response.Write(csvData);
    Response.End();
    }
    }
    }

  • Bart

    Thanks Manu,
    Your code was much more concise but it still posted with the url %20 and stuff and I finally found the key ingredient “urlDecode()”
    See code below: (this works perfectly)
    using System;
    using System.Web;
    public class Handler : IHttpHandler
    {
    public void ProcessRequest (HttpContext context) {
    string csvData = context.Request.Params[“csvdata”];
    string csvDataDecoded = context.Server.UrlDecode(csvData);
    context.Response.ContentType = “text/csv”;
    context.Response.Write(csvDataDecoded);
    context.Response.End();
    }
    public bool IsReusable {
    get {
    return false;
    }
    }
    }

  • Ryan

    do you know how to implement this in Flash, AS3? I cant seem to get it to work.

  • Hi Ryan
    I wrote it for Flex 2.0. If something has changed in Flex 3.0, not sure. I have not been doing a lot of Flash stuff lately.
    If you want AS3 file for that, you can pretty much take everything out from Script block and put in a class, refactor the code accordingly.
    Thanks
    -abdul

  • DK

    Is there a way to port this to AdvancedDataGrid?

  • Senthil

    For portg to AdvancedDataGrid, just replace datagrid with advancedDataGrid and use appropriate AdvDatagrid elements.

  • Madhava

    Is there any possible to do in reverse way. i.e., From csv/Excel to Flex using java/jsp.

    Thanks in advance

    • @Madhava: I believe, it’s totally doable. You can load csv/excel on server-side using java/jsp, pass the value to Flex via different ways.

  • Rupesh

    Thanks a lot, i was searching for a way to preserve the data formating when exporting.

  • Dimiorla

    nice app,
    i get aan error on line 11 somthing like 1061: not defined methode exportCSV of type ‘static’ Class.
    i use flex builder3 what shuld i do?
    Thanks in advance, Dimitri

  • Dimiorla

    @Abdul Qabiz
    do you have an example for us?
    please.

  • Dimiorla

    Your DataGridDataExporter is an excellent application.
    I am trying to build you example with flex builder3. I have tried many things, but I get every time an other error. I am not that experienced with AS3 so I was wondering is you could update your blog.
    Any way thanks for your contribution to the community.
    Best regards Dimitris Orlandos
    P.S My error comes up in this line.
    console.text = DataGridDataExporter.exportCSV (dg);

  • @Dimiorla It compiles fine with Flex SDK (mxmlc), I don’t know why it’s giving error in FlexBuilder 3.0. I verified and so far could not figure out, doesn’t seem to be path issue.

    Using Eclipse/FlexBuilder’s CTRL+CLICK over class (DataGridDataExporter) name in mxml code, doesn’t even open the DataGridDataExporter.as?

    I would try to figure out, it might take sometime because I don’t use FlexBuilder. I am a VIM + SDK guy :-)

    Thanks for reporting the issue, I really appreciate. And sorry about late response, you have to leave so many comments.

    -abdul

  • Dimiorla

    I don’t know is this is the best way but it work.
    What I have done is some small changes in the following lines

    DataGridCSVExportExample.mxml before

    DataGridCSVExportExample.mxml after

    DataGridDataExporter.as before
    public class DataGridDataExporter
    DataGridDataExporter.as after
    [Bindable]
    public class DataGridDataExporter

    Greetings Dimitris

  • Dimiorla

    Abdul the DataGridCSVExportExample.mxml code is not displayed in my reply
    Sorry for the extra replies maybe you can delete them.

  • Alina

    Hello! I have tried your code, it compiles fine but when I try to download the csv file, I receive an exception:
    Il s’est produit une erreur de code ActionScript :
    Error #2044: IOErrorEvent non pris en charge : text=Error #2038: Erreur d’E/S de fichier.
    So it’s an I/O exception on the file, apparently at this line:
    if (!downloadFileRef){
    downloadFileRef = new FileReference();
    }

    Would someone have an idea on this? Thank you for your code otherwise. It’s been of great help.
    Alina

  • Prachi

    I want to fetch file name passed as paramenter flex to perl script and then echo the same on my flex GUI, please let me know how can it be achieved.

    What is wrong in the following perl script as i m getting IO error
    #!C:\perl\bin\perl.exe

    use CGI qw(:standard);
    my $query = new CGI;

    print $query->param(‘filesend’);

    Flex code

    <![CDATA[
    private function onResult():void
    {
    txt.text= txt.text + "Msg1: ” + xmlService.lastResult;

    }
    ]]>

    {EdTI.text}

    <mx:Button id="EdCheck" label="Check" click="check()"

  • Jhaan

    I cannot get this example to work (export datagrid as csv and save as a .xls type). I want to export my current datagrid values as an excel spreadsheet. I only get as far as getting the user to download the file and then it gives me a message when I open it in excel: Your browser does not appear to support frame based web-pages.
    it also gives me the following message when I try opening it in notepad:

    ?xml version=”1.0″ encoding=”ISO-8859-1″ ?>

    Fleet Management Solution

    Your browser does not appear to support frame based web-pages.

    Any help will be appreciated!

  • Swapnil Shirke

    Thanks loads men.
    I wanted to export the datagrid into excel and you gave me exactly that…
    Thanks again…

  • joeboxer

    Fantastic kickstart on dg access. Helped me alot.

  • maymud

    Thank you

  • Name

    thanks for the post it was really helpfull

    cheers

  • dimiorla

    Can I show in the header string instead of the column.headerText of the datagrid a text from textarea?
    Thanks in advance, Dimitri

  • umbrellas

    About the wonderful, very pleased to see this article, learn some things, and view the text is recognized. Thank you for sharing. At the same time,i feel blue paperless recorder very much

  • flexicious

    We’ve created a datagrid component that internally ecapsulates excel, word, html, text, pdf export in addition to filter,pager footer, options persistence, and a lot more! Please feel free to check out http://www.flexicious.com

  • Negi

    @f2caf0fc293b91045035d6ca21430deb:disqus code is acceptable, but what if user want to export data in multiple sheet in one csv file?

    Is there a way to create a multiple sheet csv file in flex??

  • Yogesh

    Thanks for this useful post..

  • Manjunath Mugunda

    Hi, I have posted a sample in my blog, where grouped Headers also exported to excel, Please check there…
    http://mugunda.blogspot.com/2011/05/flex-export-advanced-datagrid-to-excel.html