Click here to Skip to main content
16,017,881 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I need to export gridview data to an excel file and for this I have written below code.

try
           {
               System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
               string attachment = "attachment; filename=MQDeatils_Homer.xls";
               Response.ClearContent();
               Response.Buffer = true;
               Response.AddHeader("content-disposition", attachment);
               Response.ContentType = "application/vnd.ms-excel";
               StringWriter stw = new StringWriter();
               HtmlTextWriter htextw = new HtmlTextWriter(stw);
               form.Controls.Add(gvMQReport);
               this.Controls.Add(form);
               form.RenderControl(htextw);
               Response.Write(stw.ToString());
               Response.End();
           }
           catch(Exception ex)
           {}


After I save and open this excel file I am getting an excel error:
"Excel cannot open this file because the file format is not valid"

1) How can I resolve this?
2) If user doesn't have excel 2003 (above code I wrote for 2003 (xls not xslx)) and having higher versions like 2007 or 2010, how to handle that?

Can anybody please help on above questions
Posted
Updated 31-Aug-10 1:20am
v2
Comments
Dalek Dave 31-Aug-10 7:20am    
Edited for Grammar.

ok add the following to your code..

C#
Response.Charset="";
//set the Charset to ""

Response.ContentType="application/vnd.xls";
// Alter the content-type to this

Response.Cache.SetCacheability(HttpCacheability.NoCache);
// and set the cacheability


and I believe it shouldnt give you problems anymore..:)
 
Share this answer
 
Comments
yadlaprasad 31-Aug-10 8:24am    
Hi thanks for your response even i added the above code lines no use. is there any alternative? still i am getting same invalid format
Try the link below:
Link-1[^]
 
Share this answer
 
2007 and higher will still open 2003, there is no problem there.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900