Tuesday, September 13, 2011

Asp.Net - Export GridView to Excel

Exporting gridview contents to excel is one of the most common requirements in many asp.net applications.

I found a helper class in the following link to be very useful-


One limitation of the class is that it doesn't work if you have grid paging turned on - it only exports the rows that are visible on the page, not the whole grid. To workaround this call the disable Gridview paging as the first line of the Export() Sub and re-enable paging as the last line of the Export() Sub.

Also to have this working with a Master Page you need to override a method called VerifyRenderingInServerForm as follows
public override void VerifyRenderingInServerForm(Control control)
{

}

If you want to remove any columns from being exported then add a int16[] parameter to the export function and call a new method (displayed below) instead of PrepareControlForExport in the export function.;
code:
private static void PrepareControlForExportMaster(Control control, Int16[] ListColumnsToRemove)
{
for (int i = 0; i
{
control.Controls.RemoveAt(ListColumnsToRemove[i]);
}
GridViewExportUtil.PrepareControlForExport(control);
}





No comments:

Post a Comment