简体   繁体   中英

Exporting a Gridview to Excel using VB.NET

I have a page with a gridview on it, which is using a master page. The export button is on the Master page from which I need to export ONLY the gridview data that is on the actual page.

There are some hidden columns on the gridview and these must not be included on the data exported to Excel.

How can I do this with out grabbing any other formatting around the gridview (ie on the page itself)?

I am basically using the code on this URL: Export Gridview Data to Excel - Change the header name (I converted to VB.NET), but it seems to be exporting ALL data on the grid to Excel, including the hidden columns.

I have been searching for a solution for quite sometime. I looked over your code before and I couldnt seem to get it working - But this was because of a lack of knowledge. So for anyone else that might sit with this same problem, here was my scenario and solution, please note that this is in VB and can be converted using any online converting tool :

Scenario : I have a master page with an export button which exports data from a gridview on a page using the masterpage.

In the Page_Load event of the page with the Gridview, i used the following code :

Dim myMasterPage As MasterPageName = Page.Master

Dim exportButton As System.Web.UI.WebControls.Button = myMasterPage.FindControl("ButExportExcel")

If (exportButton IsNot Nothing) Then 
    AddHandler exportButton.Click, AddressOf Me.ButExportExcel_Click
End If

I then created the public sub:


Private Sub ButExportExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs)

    Dim sMethod = "ButExportExcel_Click"
    Dim sErrorMessage = ""
    Dim sExportFileName As String = ""

    Try

        sExportFileName = Path.GetFileName(Request.PhysicalPath)
        sExportFileName = sExportFileName.Substring(0, sExportFileName.Length - 5) & ".xls"

        Response.Clear()
        Response.AddHeader("content-disposition", "attachment; filename=" & sExportFileName)
        Response.ContentType = "application/vnd.xls"
        Dim WriteItem As System.IO.StringWriter = New System.IO.StringWriter()
        Dim htmlText As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(WriteItem)
        SummaryGridView.AllowPaging = False
        'Dim dtSupplier As DataTable = CType(ViewState("dtSupplier"), DataTable)
        'SummaryGridView.DataSource = dtSupplier
        SummaryGridView.DataBind()
        SummaryGridView.RenderControl(htmlText)
        Response.Write(WriteItem.ToString())
        Response.End()

    Catch ex As Exception



    End Try
End Sub

Then adding the below :

Public Overrides Sub VerifyRenderingInServerForm(control As Control)
End Sub

This unfortunately means it needs to go onto every page that you want a gridview to be exported from, but it did the job for me. This only exports the data in the gridview.

I hope this helps anyone who is sitting with the same problem.

I actually found another way, which does not affect the page itself, but only needs to be done on the masterpage.

Public Overrides Sub VerifyRenderingInServerForm(control As Control) is not required :

'Export Click event in Masterpage :

Public Sub ButExportExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButExportExcel.Click

'*** take the paging and sorting out of the excel spreadsheet

Try
Dim sgv As GridView = CType(ContentPlaceHolder_body.FindControl("SummaryGridView"), GridView)
        If (sgv IsNot Nothing) Then
            sgv.AllowPaging = False
            sgv.AllowSorting = False
            sgv.DataBind()
        End If

        Dim sExportFileName As String = ""

        sExportFileName = Path.GetFileName(Request.PhysicalPath)
        sExportFileName = sExportFileName.Substring(0, sExportFileName.Length - 5) & ".xls"

        Export2(sExportFileName, sgv)

Catch ex As Exception

End Try

End Sub

'Export Sub
Public Sub Export2(ByVal fileName As String, ByVal gv As GridView)
    Dim sExportFileName As String = ""
    Dim sStringToReplace As String = ""

    gv.HeaderStyle.ForeColor = Drawing.Color.Black
    gv.HeaderStyle.BackColor = Drawing.Color.White
    gv.RowStyle.BackColor = Drawing.Color.White
    gv.HeaderStyle.Font.Bold = True
    gv.HeaderStyle.Font.Size = 10

    sExportFileName = Path.GetFileName(Request.PhysicalPath)
    sExportFileName = sExportFileName.Substring(0, sExportFileName.Length - 5) & ".xls"

    Dim attachment As String = "attachment; filename=" & sExportFileName
    HttpContext.Current.Response.ClearContent()
    HttpContext.Current.Response.AddHeader("content-disposition", attachment)
    HttpContext.Current.Response.ContentType = "application/ms-excel"
    Dim stw As New StringWriter()
    Dim htextw As New HtmlTextWriter(stw)

    Dim parent As Control = gv.Parent
    Dim GridIndex As Integer = 0
    If parent IsNot Nothing Then
        GridIndex = parent.Controls.IndexOf(gv)
        parent.Controls.Remove(gv)
    End If

    gv.RenderControl(htextw)

    If parent IsNot Nothing Then
        parent.Controls.AddAt(GridIndex, gv)
    End If

    'gv.RenderControl(htextw)
    HttpContext.Current.Response.Write(stw.ToString())
    Dim fi As New FileInfo(Server.MapPath("../JumpStart.css"))
    Dim sb As New System.Text.StringBuilder()
    Dim sr As StreamReader = fi.OpenText()
    'sStringToReplace = "class=""generalheader"""
    While sr.Peek() >= 0
        sb.Append(sr.ReadLine())
    End While
    sr.Close()

    Dim outputHtml = "<html><head><style type='text/css'>" + sb.ToString() + "</style></head>" + stw.ToString() + "</html>"

    Response.Write(outputHtml.ToString)

    'Response.Write("<html><head><style type='text/css'>" + sb.ToString() + "</style></head>" + stw.ToString() + "</html>")
    stw = Nothing
    htextw = Nothing
    Response.Flush()
    Response.[End]()


End Sub

ACA LES DEJO UNA FUNCION MENOS COMPLICADA Y FUNCIONAL PROBADA AL 2019

PARA VB.NET

Private Sub GenerarExcel()

    Dim excel As Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application()
    excel.Application.Workbooks.Add(True)
    Dim ColumnIndex As Integer = 0
    For Each col As DataGridViewColumn In GrillaReporte.Columns
        ColumnIndex += 1
        excel.Cells(1, ColumnIndex) = col.Name

    Next

    Dim rowIndex As Integer = 0
    For Each row As DataGridViewRow In GrillaReporte.Rows

        rowIndex += 1
        ColumnIndex = 0
        For Each col As DataGridViewColumn In GrillaReporte.Columns

            ColumnIndex += 1
            excel.Cells(rowIndex + 1, ColumnIndex) = row.Cells(col.Name).Value

        Next


    Next

    excel.Visible = True


End Sub

PARA C#

private void GenerarExcel() {

        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

        excel.Application.Workbooks.Add(true);

        int ColumnIndex = 0;

        foreach (DataGridViewColumn col in GrillaArticulos.Columns)
        {
            ColumnIndex++;

            excel.Cells[1, ColumnIndex] = col.Name;

        }

        int rowIndex = 0;

        foreach (DataGridViewRow row in GrillaArticulos.Rows)
        {

            rowIndex++;

            ColumnIndex = 0;

            foreach (DataGridViewColumn col in GrillaArticulos.Columns)
            {

                ColumnIndex++;

                excel.Cells[rowIndex + 1, ColumnIndex] = row.Cells[col.Name].Value;

            }

        }

        excel.Visible = true;


    }

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