export a gridview to a pdf or to excel file

Simon 386 Reputation points
2025-03-02T22:48:26.4466667+00:00

in aspx page and i am using vb.net

how can i export a gridview to a PDF or to Excel file

thamks in advence

ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
390 questions
0 comments No comments
{count} votes

Accepted answer
  1. XuDong Peng-MSFT 11,336 Reputation points Microsoft External Staff
    2025-03-03T02:46:33.3633333+00:00

    Hi @Simon,

    how can i export a gridview to a PDF or to Excel file

    If you want to export GridView to PDF, you need use the tool iTextSharp (Install-Package iTextSharp).

    Set different response types according to the different types of files that need to be exported.

    Here is a simple demo:

    aspx
    
    <form id="form1" runat="server">
        <div>
            <asp:GridView runat="server" ID="GV1" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" />
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:BoundField DataField="Description" HeaderText="Description" />
                </Columns>
            </asp:GridView>
            <br />
            <asp:Button Text="Export to Excel" ID="Export2Excel" runat="server" OnClick="Export2Excel_Click"/>
            <asp:Button Text="Export to PDF" ID="Export2PDF" runat="server" OnClick="Export2PDF_Click" />
        </div>
    </form>
    

    Rewrite the VerifyRenderingInServerForm method to prevent GridView from throw exception.

    aspx.vb
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindGrid()
        End If
    End Sub
    
    Private Sub BindGrid()
        Dim dataList As List(Of DateData) = New List(Of DateData) From {
            New DateData With {
                .ID = 1,
                .Name = "Name1",
                .Description = "Description content 1"
            },
            New DateData With {
                .ID = 2,
                .Name = "Name2",
                .Description = "Description content 2"
            },
            New DateData With {
                .ID = 3,
                .Name = "Name3",
                .Description = "Description content 3"
            }
        }
        GV1.DataSource = dataList
        GV1.DataBind()
    End Sub
    
    Public Class DateData
        Public Property ID As Integer
        Public Property Name As String
        Public Property Description As String
    End Class
    
    Protected Sub Export2Excel_Click(sender As Object, e As EventArgs)
        Response.Clear()
        Response.Buffer = True
        Response.Charset = "UTF-8"
        Response.ContentEncoding = System.Text.Encoding.UTF8
        Response.ContentType = "application/ms-excel"
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
        Using sw As StringWriter = New StringWriter()
            Using hw As HtmlTextWriter = New HtmlTextWriter(sw)
                'Disable paging To ensure all data Is exported
                GV1.AllowPaging = False
                BindGrid()
                GV1.RenderControl(hw)
                Response.Output.Write(sw.ToString())
                Response.Flush()
                Response.[End]()
            End Using
        End Using
    End Sub
    
    Protected Sub Export2PDF_Click(sender As Object, e As EventArgs)
        Response.ContentType = "application/pdf"
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        ' Create PDF document
        Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0F)
        Dim writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
        pdfDoc.Open()
        ' Create a PDF table with the same number of columns as the GridView
        Dim pdfTable As New PdfPTable(GV1.Columns.Count)
        pdfTable.WidthPercentage = 100
        ' Add table header
        For Each headerCell As TableCell In GV1.HeaderRow.Cells
            Dim pdfCell As New PdfPCell(New Phrase(headerCell.Text))
            pdfTable.AddCell(pdfCell)
        Next
        ' Add data row
        For Each row As GridViewRow In GV1.Rows
            For Each cell As TableCell In row.Cells
                Dim pdfCell As New PdfPCell(New Phrase(cell.Text))
                pdfTable.AddCell(pdfCell)
            Next
        Next
        pdfDoc.Add(pdfTable)
        pdfDoc.Close()
        Response.Write(pdfDoc)
        Response.End()
    End Sub
    
    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
    
    End Sub
    

    Best regards,

    Xudong Peng


    If the answer is the right solution, please click "Accept Answer" and kindly upvote. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.