Hi,
I am trying to export the contents of a DataGrid to Excel. I have already
found the following articles:
http://support.microsoft.com/default...b;en-us;317719
http://www.c-sharpcorner.com/Code/20...ridToExcel.asp
These methods _only_ work if the following is true:
1.) Paging and sorting is disabled; (produces error stating that controls
must reside within form tag and specify runat=server)
2.) Columns are autogenerated (unless see 3);
3.) If columns are not autogenerated template columns in the form of the
following causes errors; (cannot alter controls that contain <% %>;
<asp:TemplateCo lumn HeaderText="Day ">
<ItemTemplate >
<%# DataBinder.Eval (Container, "DataItem.DayOf Week") %>
</ItemTemplate>
</asp:TemplateCol umn>
The Code I am using is at the bottom of this post.
I was wondering how to go about the following - or if there is a 3rd party
control that does this.
Either:
1.) Pass the original datasource to some kind of custom control. This would
also be given the properties of the datasource (in my case strongly typed
collections) and the control would then loop through using reflection to
Retrieve the values and generate a new HtmlTable that is then rendered to
the Response stream.
2.) Contruct a new grid using the original and only constructing columns
specified (not sure how to manually create a grid yet.)
The first I beleive is far more extensible as it allows my object model and
any available property in it to be exported to excel, but obviously this
will have a longer dev time. Is this even possible.
Any help would be greatly appreciated.
TIA
MattC
protected void ExportToExcel(D ataGrid grid)
{
Response.Clear( );
Response.Buffer = true;
Response.Conten tType = "applicatio n/vnd.ms-excel";
Response.Charse t = String.Empty;
this.EnableView State = false;
System.IO.Strin gWriter oStringWriter = new System.IO.Strin gWriter();
System.Web.UI.H tmlTextWriter oHtmlTextWriter = new
System.Web.UI.H tmlTextWriter(o StringWriter);
this.ClearContr ols(grid);
grid.RenderCont rol(oHtmlTextWr iter);
Response.Write( oStringWriter.T oString());
Response.End();
}
protected void ClearControls(C ontrol control)
{
for (int i=control.Contr ols.Count -1; i>=0; i--)
{
ClearControls(c ontrol.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetTyp e().GetProperty ("SelectedItem" ) != null)
{
LiteralControl literal = new LiteralControl( );
control.Parent. Controls.Add(li teral);
try
{
literal.Text =
(string)control .GetType().GetP roperty("Select edItem").GetVal ue(control,null );
}
catch
{
}
control.Parent. Controls.Remove (control);
}
else
if (control.GetTyp e().GetProperty ("Text") != null)
{
LiteralControl literal = new LiteralControl( );
control.Parent. Controls.Add(li teral);
literal.Text =
(string)control .GetType().GetP roperty("Text") .GetValue(contr ol,null);
control.Parent. Controls.Remove (control);
}
}
return;
}