Friday, May 8, 2009

Get Rid of a Blank Row When Exporting to Excel

When you export a GridView to Excel using C# code similar to this:

Response.ClearContent();
Response.ContentType = "application/excel";
Response.AddHeader("content-disposition", "attachment; filename=data.xls");

Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
this.EnableViewState = false;

System.IO.StringWriter strWriter = new System.IO.StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(strWriter);

gv.RenderControl(htmlTextWriter);

htmlTextWriter.Close();
strWriter.Close();

Response.Write(strWriter.ToString());
HttpContext.Current.ApplicationInstance.CompleteRequest();

You end up with the first row being blank in Excel.

To fix this problem, you need to override the Render (HtmlTextWriter writer) method:

protected override void Render(HtmlTextWriter writer)
{
}

2 comments:

  1. I tried this. But the whole page will be blank as you are not rendering anything.

    ReplyDelete
  2. Can't say anything without seeing your code.

    ReplyDelete