【问题标题】:Export DataTable to Excel from VB.Net从 VB.Net 导出 DataTable 到 Excel
【发布时间】:2016-04-16 02:25:41
【问题描述】:

以下代码是我当前尝试从 VB.Net 中的网站按钮在 excel 中打开一些数据。我希望数据显示准系统,但网站上表格的格式始终遵循。分页和颜色使数据几乎无法读取,只能看到第一页数据。任何快速修复?我已经尝试了很多我在这里找到的东西,但无济于事。

 Private Sub DownloadExcel()

    Response.Clear()

    'Dim dt As DataTable = TryCast(ViewState("GridData"), DataTable)

    Grid_Bad_Meters.AllowPaging = False
    Grid_Bad_Meters.AllowSorting = False

    'Grid_Bad_Meters.DataSource = dt
    'Grid_Bad_Meters.DataBind()

    Dim sfile As String = "Communication_Failures" & Now.Ticks

    Response.AddHeader("content-disposition", "attachment;filename=" & sfile & ".xls")
    Response.Charset = ""

    ' If you want the option to open the Excel file without saving then 
    ' comment out the line below 
    ' Response.Cache.SetCacheability(HttpCacheability.NoCache); 
    Response.ContentType = "application/vnd.ms-excel"
    Dim stringWrite As New System.IO.StringWriter()
    Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
    Grid_Bad_Meters.RenderControl(htmlWrite)
    Response.Write(stringWrite.ToString())
    Response.End()

    'Grid_Bad_Meters.AllowPaging = True
    'Grid_Bad_Meters.AllowSorting = True
    'GridView1.DataSource = dt

    'GridView1.DataBind()


End Sub

【问题讨论】:

  • 将扩展名更改为 .csv
  • 您不是在创建 Excel 文件,而是在创建 HTML 文件并使用 Excel 扩展名和 MIME 类型来提供它。不要那样做,这是一个肮脏的黑客。使用 EPPlus、NPOI 或 Office XML SDK 等库创建真正的 Excel 文件。我在我的个人blog post 中讨论您的技术和 EPPlus。
  • 或 Office Interop/VSTA。
  • 也许您会对封闭式 XML 库感兴趣。看this

标签: asp.net vb.net excel


【解决方案1】:
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Try
            Dim ScriptManager As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            ScriptManager.RegisterPostBackControl(Me.btnExportToExcel)

    Catch ex As Exception

    End Try
End Sub



Protected Sub btnExportToExcel_Click(sender As Object, e As EventArgs) Handles btnExportToExcel.Click
    Try

        Dim sw As New System.IO.StringWriter()
        Dim hw As New System.Web.UI.HtmlTextWriter(sw)
        Dim style As String = "<style>.textmode{mso-number-format:\@;}</style>"

        Response.Clear()
        Response.Buffer = True

        Response.AddHeader("content-disposition", "attachment;filename=SignExport.xls")
        Response.Charset = ""
        Response.ContentType = "application/vnd.ms-excel"

        For i As Integer = 0 To Me.Grid_Bad_Meters.Rows.Count - 1
            Dim row As GridViewRow = Grid_Bad_Meters.Rows(i)
            row.Attributes.Add("class", "textmode")
        Next
        'lblRptHeader.RenderControl(hw)
        hw.WriteBreak()
        'lblReportDateRange.RenderControl(hw)
        Grid_Bad_Meters.RenderControl(hw)
        Response.Write(style)
        Response.Output.Write(sw.ToString())
        Response.Flush()
        Response.End()






    Catch ex As Exception


    End Try

End Sub

【讨论】:

    【解决方案2】:

    您可以使用下面提到的两种方法之一。当然,还有其他方法可以满足您的要求,例如导出到评论中提到的 csv 文件,或者使用用于 Excel 导出的 .Net 库,例如 epplus

    OpenXML 方法

    如果您正在寻找一种在不使用 html 方法的情况下导出到 Excel 的方法,那么您可以使用 OpenXML 方法,该方法通过此 URL 上的一个工作示例进行了非常清楚的解释:Export to Excel using OpenXML。这将eliminate all the CSS styles 可以与使用 html 方法导出相关联,并且您似乎正在根据原始帖子中的代码使用这种 html 方法。但是,如果您想使用 html 方法,那么下面的代码应该可以工作并消除查看 excel 文件时可能出现的所有 CSS 样式。在把它放在这里之前,我实际上已经在我的机器上尝试过这个发布的代码。

    HTML 方法

    您可以在导出方法中创建一个新的 GridView 实例,而不是使用现有实例,并将其数据绑定到与页面上现有 gridview 相同的数据,然后再将其呈现为 excel。在导出方法中数据绑定之前,您需要确保没有设置任何样式,特别是网格线设置为无,如下面的代码所示。

    您可以在此 URL 上观看有关其工作原理的实际视频: Grid Export without any CSS Styles。这就是我运行它时代码在我的笔记本电脑上的表现。

    您可以使用下面的示例代码,但请确保将数据源设置为包含原始 gridview 所有页面中所有记录的数据。我使用SqlDataSource1 作为数据源,但您可以根据您的情况用适当的方法替换它。

    Protected Sub btnExport_Click(sender As Object, e As EventArgs)
        Dim GridView2 As New GridView()
        GridView2.AllowPaging = False
        GridView2.AllowSorting = False
        GridView2.Style.Clear()
        GridView2.CellPadding = 0
        GridView2.CellSpacing = 0
        GridView2.GridLines = GridLines.None
        GridView2.BorderStyle = BorderStyle.None
        GridView2.BorderWidth = Unit.Pixel(0)
        GridView2.AlternatingRowStyle.BorderStyle = BorderStyle.None
        GridView2.DataSource = SqlDataSource1
        GridView2.DataBind()
    
        ' Clear the response  
        Response.Clear()
    
        ' Set the type and filename  
        Response.AddHeader("content-disposition", "attachment;filename=griddata.xls")
        Response.Charset = ""
        Response.ContentType = "application/vnd.xls"
    
        ' Add the HTML from the GridView to a StringWriter so we can write it out later  
        Dim sw As New System.IO.StringWriter()
        Dim hw As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(sw)
        GridView2.RenderControl(hw)
    
        ' Write out the data  
        Response.Write(sw.ToString())
        Response.[End]()
    End Sub
    Public Overrides Property EnableEventValidation() As Boolean
        Get
            Return False
        End Get
                'Do nothing
        Set
        End Set
    End Property
    Public Overrides Sub VerifyRenderingInServerForm(control As Control)
        'Allows for printing
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 2016-01-15
      相关资源
      最近更新 更多