简体   繁体   中英

Export DataTable to Excel from VB.Net

The following code is my current attempt at opening some data in excel from a website button in VB.Net. I would like the data to show up barebones, but the formatting from the table on the website always follows. The paging and colors make the data near impossible to read and can only see the first page of data. Any quick fixes? I've tried a lot of things I've found on here but to no avail.

 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
 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

You could use one of the two approaches mentioned below. Of course, there are other ways of meeting your requirement like exporting to csv file as mentioned in a comment or using a .Net library meant for Excel exporting like epplus .

OpenXML Approach

If you are looking for a way to export to Excel without using the html approach, then you can use OpenXML approach that is explained very clearly with a working example at this URL: Export to Excel using OpenXML . This will eliminate all the CSS styles that can get associated with exporting using html approach and you seem to be using this html approach according to the code in your original post. However, if you want to use the html approach, then the code below should work and eliminate all CSS styles that can come in the way when viewing the excel file. I have actually tried this posted code on my machine before putting it here.

Html Approach

You can create a new instance of GridView in your export method rather than use an existing instance, and data bind it to same data as the existing gridview on your page before rendering it to excel. Before you data bind it in the export method you need to make sure that no styles are set and specifically the grid line are set to none as in code below.

You can see an actual video of how this works at this URL : Grid Export without any CSS Styles . This was how the code behaved on my laptop when I ran it.

You can use sample code below, but make sure the data source is set to data that includes all records across all pages of original gridview. I have used SqlDataSource1 as data source but you can replace it by an appropriate method in your situation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM