469,927 Members | 1,267 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,927 developers. It's quick & easy.

Export Datagrid to Excel in C#

Ugo
Hi,
I am having a problem exporting a Datagrid to excel in asp.net. For
some reason I am getting a blank excel page. I set up in IIS the Mime for
..xls. My code is below any help would be appreciated..

Thanks

CODE:

private void ExportToExcel()
{
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.Default;
Response.Charset = "";
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
DataGrid dg = new DataGrid();
dg.DataSource = (DataSet) Cache["dataset"];
dg.DataBind();
dg.RenderControl(hw);
Response.Write(tw.ToString());
Response.Flush() ;
Response.Close();
}


Nov 16 '05 #1
1 10731
Ugo,

The reason for this is that you are indicating to IE that an Excel sheet
is being sent, but you end up sending HTML. While Excel can handle HTML
files, the mime type you are sending indicates that it is not what it is
expecting.

If anything, I would open a temp Excel sheet on the server, modify the
content (through automation), save it, and then stream the contents of the
temp file back to the user.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Ugo" <ub*******@hartco.com> wrote in message
news:eW**************@TK2MSFTNGP11.phx.gbl...
Hi,
I am having a problem exporting a Datagrid to excel in asp.net. For some reason I am getting a blank excel page. I set up in IIS the Mime for
.xls. My code is below any help would be appreciated..

Thanks

CODE:

private void ExportToExcel()
{
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.Default;
Response.Charset = "";
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
DataGrid dg = new DataGrid();
dg.DataSource = (DataSet) Cache["dataset"];
dg.DataBind();
dg.RenderControl(hw);
Response.Write(tw.ToString());
Response.Flush() ;
Response.Close();
}

Nov 16 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Bidarkota | last post: by
3 posts views Thread by Bidarkota | last post: by
reply views Thread by sunilkumar Reddy via DotNetMonster.com | last post: by
6 posts views Thread by Sridhar | last post: by
4 posts views Thread by Frank | last post: by
19 posts views Thread by cj2 | last post: by
5 posts views Thread by Reggie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.