Search code examples
vb.netexcelexport-to-excel

Issue with Excel file after exporting using VB.net


Im sitting with a very very strange problem and I have no idea what the problem is.

I am using the following code to export data from a RadGrid:

Public Sub Export()
    Dim GridView1 As New GridView()
    GridView1.AllowPaging = False
    rgrvResourceTasks.DataBind()
    GridView1.DataSource = SqlDataSource_Resources
    GridView1.DataBind()

    HttpContext.Current.Response.Clear()
    HttpContext.Current.Response.Buffer = True
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=ResourceTaskExport.xls")
    Response.ContentEncoding = Encoding.UTF8
    HttpContext.Current.Response.Charset = ""
    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"

    Dim sw As New StringWriter()
    Dim hw As New HtmlTextWriter(sw)

    For i As Integer = 0 To GridView1.Rows.Count - 1
        'Apply text style to each Row
        GridView1.Rows(i).Attributes.Add("class", "textmode")
    Next

    GridView1.RenderControl(hw)

    'style to format numbers to string
    Dim style As String = "<style> .textmode{mso-number-format:\@;}</style>"
    HttpContext.Current.Response.Write(style)
    HttpContext.Current.Response.Output.Write(sw.ToString())
    HttpContext.Current.Response.Flush()
    HttpContext.Current.Response.End()

    Response.Clear()

    'Response.Write("<script language=""javascript"">self.close();</script>")
    System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "Close_Window", "self.close();", True)

End Sub

The file exports just fine. But when I open it up, its as if nothing opened(black background, no headers showing etc) - Not even a blank sheet. However, when I open it up in notepad, there is data(html format). When I copy that and paste it into a new excel worksheet, it displays the data as it should. When I save it as an html file, it displays the data as it should. But it just will not open it up in excel after exporting.

What could be the issue ? Im using MS Excel 2016.


Solution

  • This seems to be an issue with Excel. See this article about it: HTML files with .XLS not opening outside protected view in Excel 2010, 2013, and 2016