使用VB.net导出后出现Excel文件问题

时间:2016-08-12 13:13:56

标签: vb.net excel export-to-excel

我坐在一个非常奇怪的问题上,我不知道问题是什么。

我使用以下代码从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

文件导出就好了。但是,当我打开它时,它似乎没有打开(黑色背景,没有标题显示等) - 甚至不是一张白纸。但是,当我在记事本中打开它时,有数据(html格式)。当我将其复制并粘贴到新的Excel工作表中时,它会按原样显示数据。当我将其保存为html文件时,它会按原样显示数据。但它只是不会在出口后在excel中打开它。

可能是什么问题?我正在使用MS Excel 2016。

1 个答案:

答案 0 :(得分:0)

这似乎是Excel的一个问题。请参阅此文章:HTML files with .XLS not opening outside protected view in Excel 2010, 2013, and 2016