20070515

Exporting Datagrid data to excel

Add to Technorati Favorites
This is a updated version of http://www.cflex.net/showFileDetails.cfm?ObjectID=298&Object=File&ChannelID=1

Algo:
===
1. Convert the datagrid data to csv string
2. Post data to a servlet
3. Servlet returns the same csv string back with content -type of the HTTPResponse set to "application/ms-excel"


1. Convert the datagrid data to csv string
This is a generic version and should work with any datagrid.

public class DataGridCSVTransformer
{
private static var csvSeparator : String = "\t";
private static var lineSeparator = "\n";

public static function toCSV(dg : DataGrid) : String
{
var str : String = "";
for(var i : int = 0; i <>
{
var dgc : DataGridColumn = dg.columns[i];
if(!dgc.visible)
continue;
str += "\""+dgc.headerText+"\"";
if(i < (dg.columnCount -1))
str += csvSeparator;
}
str += "\r\n";
var rowCount : int = dg.dataProvider.length;

for(var j:int = 0; j <>
{
for(var k : int = 0; k <>
{
var dgc : DataGridColumn = dg.columns[k];
if(!dgc.visible)
continue;
var obj : Object = null;
if(dg.dataProvider is ArrayCollection)
obj = (dg.dataProvider as ArrayCollection).getItemAt(j);
else
obj = (dg.dataProvider as Array)[j];

str += "\""+dgc.itemToLabel(obj)+"\"";
if(k < (dg.columnCount -1))
str += csvSeparator;
}
if(j < (rowCount - 1))
str += lineSeparator;
}

Alert.show("String :: "+str);
return str;
}
}

2. Post the CSV data to servlet
private function doPost(event:Event) : void
{
var csvConverter :
DataGridCSVTransformer = new DataGridCSVTransformer();
var dgCSV : String =
csvConverter.toCSV(dg);
var url : String = "http://localhost:8080/flextest/reports/genreport";
var urlr : URLRequest = new URLRequest(url);
urlr.method = "POST";
var urlv : URLVariables = new URLVariables();
urlv.reportdata =
dgCSV;
urlr.data = urlv;
navigateToURL(urlr,"_blank");
}

3. Servlet returns the same csv string back with content -type of the HTTPResponse set to "application/ms-excel"

public void generateReport(HTTPServletRequest req, HTTPServletResponse res)
throws ServletException, IOException
{
String csvData = req.getParameter("reportData");
res.setContentType("application/ms-excel");
res.getOutputStream().print(csvData);
}

4 comments:

Luis M Cantu said...

The Code here is corrupted can you post the complete code of the class DataGridCSVTransformer?

별따는수야 said...

very very thank you!!!
this post is very helpful to me!!!!

Dharmendra said...

This solution does not seems to be working when I run jboss deplyed flex's swf file in Dot Net Container.
I always receive empty value in servlet.

What could be the possible reason for this.

Regards,
Dharmendra

abhishek said...

plz give full working code