tags:

views:

15

answers:

1

Ok so I am trying to export the contents of DataGrid control to an excel file.

Here is my code:

Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/ms-excel";
Response.AppendHeader("content-disposition", "inline; filename=Report.csv");
Response.TransmitFile(Server.MapPath("~/GridData.xls"));

I am basically taking the DataGrid control, converting it to a DataTable, and then writing it out to a StreamWriter, saving as an XLS file.

The problem happens when I go to save the file. I can save it, open it and everything, but when I open it, I see the entire content of the page as well. According to MSDN I have to clear the response, which is what I have done above in the first 3 lines. What am I missing?

+1  A: 

I found out the reason why this is happening.

I added in

Response.AppendHeader("content-length", reportFileLength.ToString());

Where reportFileLength is the length of a file I took from a FileStream object.

As soon as I specified that, only that amount of info was being written to the reponse stream and it solved this weird problem.

But it just seemed weird to me that Response.Clear(), Response.ClearContent() are not really working as intuitively as it would seem. Little misleading there.

Steven Wright