Saturday, 16 February 2013

Exporting a asp.NET GridView to csv format


If you need to export the contents of a GridView to CSV format, one way is to use this static class and static method ExportToCSV which take a GridView object as a param.

This loops through all headers and rows in grid and exports them all as comma delimited csv and pushes the response to the screen to allow the user to either save or open. On clicking open , it opens the response in Excel by default.

Important points to note in this code are :AddHeader & ContentType properties of the Response. This ensures you create a CSV.

/// <summary>

/// Exports a Grid to CSV format

/// </summary>

/// <param name="grid">The grid.</param>

public static void ExportToCSV(GridView grid, int jurisdictionId)
{


StringBuilder sb = new StringBuilder();

bool addExtraROIFields = false;
addExtraROIFields = jurisdictionId ==
Constant.Juristiction_ROI;

////Loop through all our grid columns to build up our string

for (int k = 0; k < grid.Columns.Count; k++)
{


////Check jurisdiction , for GB , we dont want IBAN or Swift coming out , which are column 3 , 4

if (k == 3 || k == 4)
{


///If we are to add extra fields , go ahead ...

if (addExtraROIFields)
{


//add column text , plus a comma separator
sb.Append(grid.Columns[k].HeaderText +
',');
}

}

else
{

sb.Append(grid.Columns[k].HeaderText +
',');
}

}

//append new line
 sb.Append(
"\r\n");
////Loop through all our rows and append each with comma
for (int i = 0; i < grid.Rows.Count; i++)
{

for (int k = 0; k < grid.Columns.Count; k++)
{
////Check jurisdiction , for GB , we dont want IBAN or Swift coming out , which are column 3 , 4

if (k == 3 || k == 4)
{


///If we are to add extra fields , go ahead ...

if (addExtraROIFields)
{


//add row text , plus a comma separator
sb.Append(grid.Rows[i].Cells[k].Text +
',');
}

}



else
{

sb.Append(grid.Rows[i].Cells[k].Text +
',');
}

}
//append new line
sb.Append(
"\r\n");
}
///Make sure you strip out spaces
string theResult = sb.ToString().Replace("&nbsp;""");

///Push it out to the screen , to prompt user to open or save
HttpContext.Current.Response.Clear();

HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.csv");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/text";
HttpContext.Current.Response.Output.Write(theResult);
HttpContext.Current.Response.Flush();

HttpContext.Current.Response.End();

 }

No comments:

Post a Comment