Exporting DataGrid to CSV using Flex with Java

12 06 2009

Exporting of DataGrid data to CSV format in Flex and Action Script 3.0

Converting Data Grid data to String (csv format):


private function exportToCSV():String {
 var xmlListColl:XMLListCollection = new XMLListCollection;
 xmlListColl= myDataGrid.dataProvider as XMLListCollection;

var csvData:String = '';
 // To get Headers
 var attrList:XMLList = xmlListColl[0].@*;
 for (var i:int = 0; i < attrList.length(); i++) {
 csvData += attrList[i].name() + ',';
 }

 csvData += '\n';
 //    To get actual data
 for ( var j:int = 0; j &amp;amp;lt; xmlListColl.length; j++) {
 var record:XMLList = xmlListColl[j].@*;
 for ( var k:int = 0; k < record.length(); k++) {
 csvData += record[k] + ',';
 }
 csvData += '\n';
 }
 return csvData;
 }

The above function will convert DataGrid data(if its data is in xml format) to csv format.

If you want to create a csv file then you have to send to the server and then download the csv file.

For sending this data to server side (implemented in java) you can use simple HTTPService in flex

and sending with the paramater – csvData what we created in above function.

In Java we will use a simple servlet.


byte[] output = request.getParameter( "input" ).getBytes();

 response.setContentType("text/csv");

 response.setHeader("Content-Disposition", "attachment; name=\"Result\"; filename=\"Result.csv\"");

 response.setContentLength( output.length );

 response.getOutputStream().write( output );

Just copy the above code in servlet that will return an output stream. Take this responce to flex

use ExternalInterface call to accept that stream and it will show you dialog box with Open and Save option

in this way we can export the datagrid data to a csv file.








Follow

Get every new post delivered to your Inbox.