Click here to Skip to main content
15,743,427 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.Buffer = true;
       Response.AddHeader("content-disposition", "attachment;filename=VIPadmVisitors.xls");
       Response.Charset = "";
       Response.ContentType = "application/";
       Response.ContentEncoding = Encoding.Unicode;

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

           //To Export all pages
           gvVisitedVisitors.AllowPaging = false;
           gvVisitedVisitors.Columns[1].Visible = false;

           //style to format numbers to string
           //string style = @"<style> .textmode { mso-number-format:\@; } </style>";
           string style = @"<style> td { mso-number-format:\@;} </style>";
Updated 15-Jul-22 0:02am

1 solution

The ContentType for xlsx should be

Additional Information: c# - MIME-Type for Excel XML (ASP.NET 3.5) - Stack Overflow[^]
Share this answer
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