Question : Export Datagrid to excel

the following code exports a datagrid to excel, but here is the problem, when opening in Office 2007 it give an error that that states -

The file you are trying to open is a different format than than specified by extension, Verify that the file is not corrupt and is from a trusted source before opending the file.  Do you wnat to open now.  If I open it it works just fine and can then save to new format.

When I open it opens fine but users might get the wrong impression that its messed up.  here is the code I am using.  how can I fix this so that if users are suing either version of Office, 2003 or 2007 it will open and save properly.

Sub RenderGridToExcelFormat(ByVal grid As DataGrid, ByVal saveAsFile As String)
        ' Excel rows limit is 65536
        If grid.Items.Count.ToString + 1 < 65536 Then
            HttpContext.Current.Response.Clear()
            HttpContext.Current.Response.ContentType = "application/vnd.xlsx"
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" & saveAsFile & ".xls")
            ' Remove the charset from the Content-Type header.
            HttpContext.Current.Response.Charset = ""
            'HttpContext.Current.Response.WriteFile("style.txt")
            ' Turn off the view state.
            grid.EnableViewState = False
            Dim tw As New System.IO.StringWriter
            Dim hw As New System.Web.UI.HtmlTextWriter(tw)
            grid.RenderControl(hw)
            ' Write the HTML back to the browser.
            HttpContext.Current.Response.Write(tw.ToString())
            ' End the response.
            HttpContext.Current.Response.End()
        Else
            HttpContext.Current.Response.Write("Too many rows - Export to Excel not possible")
        End If
    End Sub


Answer : Export Datagrid to excel

It seems to be an Office bug.

Check this thread:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1681252&SiteID=1

And this blog:
http://www.itexperience.net/2008/03/17/excel-2007-error-different-format-than-specified-by-the-file-extension/

There are plenty of webs talking about this. Sorry.
Random Solutions  
 
programming4us programming4us