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.





Parsing CSV data

17 11 2008

Parsing CSV data: Its a simple file with values separated by coma(“,”) or pipe(“|”). It can be with .txt or .csv as the extension of the file. If the file is with .txt you can just read the file as normal. Even .csv is a plain text file with coma separated values, some times it may show junk values.

For this you just convert the file name as filename.txt

Here is the code for that.

File file = new File(“csvFile.txt”);
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader inputStream = new InputStreamReader(fileStream);
BufferedReader buffer = new BufferedReader(inputStream);
String line = “”;
while ((line = buffer.readLine()) != null) {
StringTokenizer token = new StringTokenizer(line, “,”);
ProductDataFeeding dataFeeding = new ProductDataFeeding();
while (token.hasMoreTokens()) {
System.out.println(“value====” + token.nextToken());
}
}

If the file is .csv

File file = new File(“csvFile.csv”);

file.renameTo(new File(“textFile.txt”));

and the remaining code is same.








Follow

Get every new post delivered to your Inbox.