problem exporting datagrid to excel
I am trying to send the contents of a datagrid to excel using C#. The code is as follows:
private void exportButton_Click(object sender, System.EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
hw.RenderBeginTag(System.Web.UI.HtmlTextWriterTag. Html);
this.ClearControls(reportGrid);
reportGrid.RenderControl(hw);
hw.RenderEndTag();
Response.Write(tw);
Response.End();
}
private void ClearControls(Control control)
{
for (int i=control.Controls.Count -1; i>=0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text = (string)control.GetType().GetProperty("SelectedIte m").GetValue(control,null);
}
catch
{
}
control.Parent.Controls.Remove(control);
}
else
if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text = (string)control.GetType().GetProperty("Text").GetV alue(control,null);
control.Parent.Controls.Remove(control);
}
}
return;
}
When running the code only the first column appears in the spreadsheet. What do I need to do to fix this problem?
Thanks,
KSCDAVE
|