Click here to Skip to main content
16,015,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi friends, when i am trying to get the data from Gridview to excel data, when i am open the excel file, the file you are trying to open fileanme.xls is in a different format than specified by the file extension, when i click yes in that time only excel is open, but my client requirement is we need to directly open the excel without click yes button.
For this i tried different formats in my code xls,xlsx,csv................but not working

What I have tried:

protected void ExportToExcel(object sender, EventArgs e)
   {
       Response.Clear();
       Response.Buffer = true;
       Response.AddHeader("content-disposition", "attachment;filename=VIPadmVisitors.xls");
       Response.Charset = "";
       Response.ContentType = "application/vnd.ms-excel";
       Response.ContentEncoding = Encoding.Unicode;
       Response.BinaryWrite(Encoding.Unicode.GetPreamble());

       using (StringWriter sw = new StringWriter())
       {
           HtmlTextWriter hw = new HtmlTextWriter(sw);

           //To Export all pages
           gvVisitedVisitors.AllowPaging = false;
           //this.BindGrid();
           gvVisitedVisitors.Columns[1].Visible = false;
           gvVisitedVisitors.RenderControl(hw);

           //style to format numbers to string
           //string style = @"<style> .textmode { mso-number-format:\@; } </style>";
           string style = @"<style> td { mso-number-format:\@;} </style>";
           Response.Write(style);
           Response.Output.Write(sw.ToString());
           Response.Flush();
           Response.End();
       }
   }
Posted
Updated 15-Jul-22 0:02am

1 solution

The ContentType for xlsx should be
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet


Additional Information: c# - MIME-Type for Excel XML (ASP.NET 3.5) - Stack Overflow[^]
 
Share this answer
 
v2
Comments
Govardhanudu Gajula 5-Dec-17 2:30am    
when i use application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
i am getting result in excel like below

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