In this article I will explain with an example, how to export GridView to Word, Excel, PDF and CSV formats in ASP.Net using C# and VB.Net.
	
		Exporting GridView to Word, Excel and CSV can be easily achieved using ASP.Net without any third party tools, but for exporting to PDF iTextSharp library will be used.
	
		This article will illustrate, how to export all Pages of GridView with Paging Enabled to Word, Excel, PDF and CSV file along with formatting i.e. Styles and Colors in ASP.Net.
	
		 
	
		 
	
		Download iTextSharp and XmlWorkerHelper Libraries
	
		You can download the iTextSharp and XmlWorkerHelper libraries from the following links.
	
	
	
	
		 
	
		 
	
		Database
	
		For this article I am making use of the Microsoft’s Northwind Database. You can download it from here.
	
	
		 
	
		 
	
		HTML Markup
	
		The HTML Markup consists of:
	
		GridView – For displaying data.
	
		Columns
	
		GridView consists of three BoundField columns.
	
		 
	
		Properties
	
		AllowPaging – For enabling paging in the GridView control. Here it is set to true.
	
		 
	
		Events
	
		The GridView has been assigned with on OnPageIndexChanging event handler.
	
		 
	
		Button – For exporting GridView data to Word, Excel, PDF and CSV.
	
		The Buttons have been assigned with OnClick event handlers.
	
		
			<asp:GridView ID="gvCustomers" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
		
			    Font-Names="Arial" Font-Size="10" RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White"
		
			    AlternatingRowStyle-ForeColor="#000" runat="server" AutoGenerateColumns="false"
		
			    AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging">
		
			    <Columns>
		
			        <asp:BoundField DataField="ContactName" HeaderText="Contact Name" ItemStyle-Width="150px" />
		
			        <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="100px" />
		
			        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100px" />
		
			    </Columns>
		
			</asp:GridView>
		
			<br />
		
			<asp:Button ID="btnExcel" runat="server" Text="Export To Excel" OnClick="ExportToExcel" Width="120" />
		
			<asp:Button ID="btnWord" runat="server" Text="Export To Word" OnClick="ExportToWord" Width="120" />
		
			<br />
		
			<br />
		
			<asp:Button ID="btnCSV" runat="server" Text="Export To CSV" OnClick="ExportToCSV" Width="120" />
		
			<asp:Button ID="btnPDF" runat="server" Text="Export To PDF" OnClick="ExportToPDF" Width="120" />
	 
	
		 
	
		 
	
		Namespaces
	
		You will need to import the following namespaces.
	
		C#
	
		
			using System.IO;
		
			using System.Text;
		
			using System.Data;
		
			using System.Drawing;
		
			using System.Data.SqlClient;
		
			using System.Configuration;
		
			using iTextSharp.text;
		
			using iTextSharp.text.pdf;
		
			using iTextSharp.tool.xml;
	 
	
		 
	
		VB.Net
	
		
			Imports System.IO
		
			Imports System.Text
		
			Imports System.Data
		
			Imports System.Drawing
		
			Imports System.Data.SqlClient
		
			Imports System.Configuration
		
			Imports iTextSharp.text
		
			Imports iTextSharp.text.pdf
		
			Imports iTextSharp.tool.xml
	 
	
		 
	
		 
	
		Binding the GridView
	
		Inside the Page Load event handler, the GridView is populated with records fetched from the Customers Table of the Northwind Database.
	
		C#
	
		
			protected void Page_Load(object sender, EventArgs e)
		
			{
		
			    if (!this.IsPostBack)
		
			    {
		
			        this.BindGrid();
		
			    }
		
			}
		
			 
		
			private void BindGrid()
		
			{
		
			    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
		
			    using (SqlConnection con = new SqlConnection(constr))
		
			    {
		
			        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
		
			        {
		
			            using (SqlDataAdapter sda = new SqlDataAdapter())
		
			            {
		
			                cmd.Connection = con;
		
			                sda.SelectCommand = cmd;
		
			                using (DataTable dt = new DataTable())
		
			                {
		
			                    sda.Fill(dt);
		
			                    gvCustomers.DataSource = dt;
		
			                    gvCustomers.DataBind();
		
			                }
		
			            }
		
			        }
		
			    }
		
			}
	 
	
		 
	
		VB.Net
	
		
			Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
		
			    If Not IsPostBack Then
		
			        Me.BindGrid()
		
			    End If
		
			End Sub
		
			 
		
			Private Sub BindGrid()
		
			    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
		
			    Using con As New SqlConnection(constr)
		
			        Using cmd As New SqlCommand("SELECT * FROM Customers")
		
			            Using sda As New SqlDataAdapter()
		
			                cmd.Connection = con
		
			                sda.SelectCommand = cmd
		
			                Using dt As New DataTable()
		
			                    sda.Fill(dt)
		
			                    gvCustomers.DataSource = dt
		
			                    gvCustomers.DataBind()
		
			                End Using
		
			            End Using
		
			        End Using
		
			    End Using
		
			End Sub
	 
	
		 
	
		 
	
		Implement Paging in GridView
	
		Inside the OnPageIndexChanging event handler, the PageIndex property of the GridView is updated with the new Page Number which was clicked.
	
		Finally, the GridView is populated using the BindGrid method which in-turn displays the new GridView page.
	
		C#
	
		
			protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
		
			{
		
			    gvCustomers.PageIndex = e.NewPageIndex;
		
			    this.BindGrid();
		
			}
	 
	
		 
	
		VB.Net
	
		
			Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs)
		
			    gvCustomers.PageIndex = e.NewPageIndex
		
			    Me.BindGrid()
		
			End Sub
	 
	
		 
	
		 
	
		Exporting GridView to Word document with Formatting
	
		When the Export Button is clicked,the Response class properties are set.
	
		1. Content-Disposition – It is a response header indicating, the download file is an attachment and allows setting the file name.
	
	
		 
	
		2. ContentType – It informs the Browser about the file type. In this case it is Word document.
	
		 
	
		Next, the StringWriter and HtmlTextWriter class objects are created and the Paging is disabled for the GridView by setting the AllowPaging property to false and the GridView is again populated with records fetched from the database by making call to the BindGrid method.
	
		Then, a FOR EACH loop is executed over the GridView rows and the style and formatting are applied to the Header Row and Alternating Row of the GridView control.
	
		Note: The colors are applied to individual cell of each Row and not to the whole Row as if this is not done then the color will spread on all cells of the Excel sheet.
	
		 
	
		Finally, StringWriter object is written to the Response which initiates the File download operation.
	
		C#
	
		
			protected void ExportToWord(object sender, EventArgs e)
		
			{
		
			    Response.Clear();
		
			    Response.Buffer = true;
		
			    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.doc");
		
			    Response.Charset = "";
		
			    Response.ContentType = "application/vnd.ms-word";
		
			    using (StringWriter sw = new StringWriter())
		
			    {
		
			        HtmlTextWriter hw = new HtmlTextWriter(sw);
		
			 
		
			        //To Export all pages.
		
			        gvCustomers.AllowPaging = false;
		
			        this.BindGrid();
		
			 
		
			        gvCustomers.HeaderRow.BackColor = Color.White;
		
			        foreach (TableCell cell in gvCustomers.HeaderRow.Cells)
		
			        {
		
			            cell.BackColor = gvCustomers.HeaderStyle.BackColor;
		
			        }
		
			        foreach (GridViewRow row in gvCustomers.Rows)
		
			        {
		
			            row.BackColor = Color.White;
		
			            foreach (TableCell cell in row.Cells)
		
			            {
		
			                if (row.RowIndex % 2 == 0)
		
			                {
		
			                    cell.BackColor = gvCustomers.AlternatingRowStyle.BackColor;
		
			                }
		
			                else
		
			                {
		
			                    cell.BackColor = gvCustomers.RowStyle.BackColor;
		
			                }
		
			            }
		
			        }
		
			 
		
			        gvCustomers.RenderControl(hw);
		
			 
		
			        Response.Output.Write(sw.ToString());
		
			        Response.Flush();
		
			        Response.End();
		
			    }
		
			}
	 
	
		 
	
		VB.Net
	
		
			Protected Sub ExportToWord(ByVal sender As Object, ByVal e As EventArgs)
		
			    Response.Clear()
		
			    Response.Buffer = True
		
			    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.doc")
		
			    Response.Charset = ""
		
			    Response.ContentType = "application/vnd.ms-word"
		
			 
		
			    Using sw As StringWriter = New StringWriter()
		
			        Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
		
			 
		
			        'To Export all pages.
		
			        gvCustomers.AllowPaging = False
		
			        Me.BindGrid()
		
			 
		
			        gvCustomers.HeaderRow.BackColor = Color.White
		
			        For Each cell As TableCell In gvCustomers.HeaderRow.Cells
		
			            cell.BackColor = gvCustomers.HeaderStyle.BackColor
		
			        Next
		
			 
		
			        For Each row As GridViewRow In gvCustomers.Rows
		
			            row.BackColor = Color.White
		
			 
		
			            For Each cell As TableCell In row.Cells
		
			 
		
			                If row.RowIndex Mod 2 = 0 Then
		
			                    cell.BackColor = gvCustomers.AlternatingRowStyle.BackColor
		
			                Else
		
			                    cell.BackColor = gvCustomers.RowStyle.BackColor
		
			                End If
		
			            Next
		
			        Next
		
			 
		
			        gvCustomers.RenderControl(hw)
		
			        Response.Output.Write(sw.ToString())
		
			        Response.Flush()
		
			        Response.End()
		
			    End Using
		
			End Sub
	 
	
		 
	
		 
	
		Exporting GridView to Excel with Formatting
	
		When the Export Button is clicked,the Response class properties are set.
	
		1. Content-Disposition – It is a response header indicating, the download file is an attachment and allows setting the file name.
	
	
		 
	
		2. ContentType – It informs the Browser about the file type. In this case it is Excel file.
	
		 
	
		Next, the StringWriter and HtmlTextWriter class objects are created and the Paging is disabled for the GridView by setting the AllowPaging property to false and the GridView is again populated with records fetched from the database by making call to the BindGrid method.
	
		Then, a FOR EACH loop is executed over the GridView rows and the style and formatting are applied to the Header Row and Alternating Row of the GridView control.
	
		Note: The colors are applied to individual cell of each Row and not to the whole Row as if this is not done then the color will spread on all cells of the Excel sheet.
	
		 
	
		After that, CSS class named textmode is applied to each cell of the GridView. This class makes sure that all the contents are rendered in Text format (mso number format).
	
		Note: The mso number format style prevents large numbers from getting converted to exponential values.
	
		 
	
		Finally, StringWriter object is written to the Response which initiates the File download operation.
	
		C#
	
		
			protected void ExportToExcel(object sender, EventArgs e)
		
			{
		
			    Response.Clear();
		
			    Response.Buffer = true;
		
			    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
		
			    Response.Charset = "";
		
			    Response.ContentType = "application/vnd.ms-excel";
		
			    using (StringWriter sw = new StringWriter())
		
			    {
		
			        HtmlTextWriter hw = new HtmlTextWriter(sw);
		
			 
		
			        //To Export all pages.
		
			        gvCustomers.AllowPaging = false;
		
			        this.BindGrid();
		
			 
		
			        gvCustomers.HeaderRow.BackColor = Color.White;
		
			        foreach (TableCell cell in gvCustomers.HeaderRow.Cells)
		
			        {
		
			            cell.BackColor = gvCustomers.HeaderStyle.BackColor;
		
			        }
		
			        foreach (GridViewRow row in gvCustomers.Rows)
		
			        {
		
			            row.BackColor = Color.White;
		
			            foreach (TableCell cell in row.Cells)
		
			            {
		
			                if (row.RowIndex % 2 == 0)
		
			                {
		
			                    cell.BackColor = gvCustomers.AlternatingRowStyle.BackColor;
		
			                }
		
			                else
		
			                {
		
			                    cell.BackColor = gvCustomers.RowStyle.BackColor;
		
			                }
		
			                cell.CssClass = "textmode";
		
			            }
		
			        }
		
			        gvCustomers.RenderControl(hw);
		
			 
		
			        //Style to format numbers to string.
		
			        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
		
			        Response.Write(style);
		
			        Response.Output.Write(sw.ToString());
		
			        Response.Flush();
		
			        Response.End();
		
			    }
		
			}
	 
	
		 
	
		VB.Net
	
		
			Protected Sub ExportToExcel(sender As Object, e As EventArgs)
		
			    Response.Clear()
		
			    Response.Buffer = True
		
			    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
		
			    Response.Charset = ""
		
			    Response.ContentType = "application/vnd.ms-excel"
		
			    Using sw As New StringWriter()
		
			        Dim hw As New HtmlTextWriter(sw)
		
			 
		
			        'To Export all pages.
		
			        gvCustomers.AllowPaging = False
		
			        Me.BindGrid()
		
			 
		
			        gvCustomers.HeaderRow.BackColor = Color.White
		
			        For Each cell As TableCell In gvCustomers.HeaderRow.Cells
		
			            cell.BackColor = gvCustomers.HeaderStyle.BackColor
		
			        Next
		
			        For Each row As GridViewRow In gvCustomers.Rows
		
			            row.BackColor = Color.White
		
			            For Each cell As TableCell In row.Cells
		
			                If row.RowIndex Mod 2 = 0 Then
		
			                    cell.BackColor = gvCustomers.AlternatingRowStyle.BackColor
		
			                Else
		
			                    cell.BackColor = gvCustomers.RowStyle.BackColor
		
			                End If
		
			                cell.CssClass = "textmode"
		
			            Next
		
			        Next
		
			 
		
			        gvCustomers.RenderControl(hw)
		
			 
		
			        'Style to format numbers to string.
		
			        Dim style As String = "<style> .textmode { mso-number-format:\@; } </style>"
		
			        Response.Write(style)
		
			        Response.Output.Write(sw.ToString())
		
			        Response.Flush()
		
			        Response.End()
		
			 
		
			    End Using
		
			End Sub
	 
	
		 
	
		 
	
		Exporting GridView to PDF with Formatting
	
		When the Export Button is clicked,the Response class properties are set.
	
		1. Content-Disposition – It is a response header indicating, the download file is an attachment and allows setting the file name.
	
	
		 
	
		2. ContentType – It informs the Browser about the file type. In this case it is PDF.
	
		The Paging is disabled for the GridView by setting the AllowPaging property to false and the GridView is again populated with records fetched from the database by making call to the BindGrid method.
	
		Next, the GridView is rendered into an HTML string using HtmlTextWriter and then, the generated HTML is added to the iTextSharp PDF document using Document class.
	
		After that, the PDF document is opened and the GridView data is written using ParseXHtml method of XmlWorkerHelper class.
	
		Finally, StringWriter object is written to the Response which initiates the File download operation.
	
		C#
	
		
			protected void ExportToPDF(object sender, EventArgs e)
		
			{
		
			    Response.Clear();
		
			    Response.Buffer = true;
		
			    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
		
			    Response.Charset = "";
		
			    Response.ContentType ="application/pdf";
		
			 
		
			    //To Export all pages.
		
			    gvCustomers.AllowPaging = false;
		
			    this.BindGrid();
		
			 
		
			    using (StringWriter sw = new StringWriter())
		
			    {
		
			        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
		
			        {
		
			            gvCustomers.RenderControl(hw);
		
			            using (StringReader sr = new StringReader(sw.ToString()))
		
			            {
		
			                using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f))
		
			                {
		
			                    using (PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream))
		
			                    {
		
			                        pdfDoc.Open();
		
			                        XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
		
			                        pdfDoc.Close();
		
			                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
		
			                        Response.Write(pdfDoc);
		
			                        Response.End();
		
			                    }
		
			                }
		
			            }
		
			        }
		
			    }
		
			}
	 
	
		 
	
		VB.Net
	
		
			Protected Sub ExportToPDF(ByVal sender As Object, ByVal e As EventArgs)
		
			    Response.Clear()
		
			    Response.Buffer = True
		
			    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
		
			    Response.Charset = ""
		
			    Response.ContentType = "application/pdf"
		
			 
		
			    'To Export all pages.
		
			    gvCustomers.AllowPaging = False
		
			    Me.BindGrid()
		
			 
		
			    Using sw As StringWriter = New StringWriter()
		
			        Using hw As HtmlTextWriter = New HtmlTextWriter(sw)
		
			            gvCustomers.RenderControl(hw)
		
			            Using sr As StringReader = New StringReader(sw.ToString())
		
			                Using pdfDoc As Document = New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
		
			                    Using writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
		
			                        pdfDoc.Open()
		
			                        XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr)
		
			                        pdfDoc.Close()
		
			                        Response.Cache.SetCacheability(HttpCacheability.NoCache)
		
			                        Response.Write(pdfDoc)
		
			                        Response.End()
		
			                    End Using
		
			                End Using
		
			            End Using
		
			        End Using
		
			    End Using
		
			End Sub
	 
	
		 
	
		 
	
		Exporting GridView to CSV file
	
		When the Export Button is clicked,the Response class properties are set.
	
		1. Content-Disposition – It is a response header indicating, the download file is an attachment and allows setting the file name.
	
	
		 
	
		2. ContentType – It informs the Browser about the file type. In this case it is CSV file.
	
		 
	
		The Paging is disabled for the GridView by setting the AllowPaging property to false and the GridView is again populated with records fetched from the database by making call to the BindGrid method.
	
		Next, the StringBuilder class object is created and a FOR EACH loop is executed over the Header row cells of the GridView and value of each cell added to the StringBuilder object with comma separated (delimited) string.
	
		Then, a FOR EACH loop is executed over the GridView Rows and Columns and a comma separated (delimited) string is generated.
	
		Finally, StringBuilder object is written to the Response which initiates the File download operation.
	
		C#
	
		
			protected void ExportToCSV(object sender, EventArgs e)
		
			{
		
			    Response.Clear();
		
			    Response.Buffer = true;
		
			    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv");
		
			    Response.Charset = "";
		
			    Response.ContentType = "text/csv";
		
			 
		
			    //To Export all pages.
		
			    gvCustomers.AllowPaging = false;
		
			    this.BindGrid();
		
			 
		
			    StringBuilder sb = new StringBuilder();
		
			    foreach (TableCell cell in gvCustomers.HeaderRow.Cells)
		
			    {
		
			        //Append data with separator.
		
			        sb.Append(cell.Text + ',');
		
			    }
		
			    //Append new line character.
		
			    sb.Append("\r\n");
		
			 
		
			    foreach (GridViewRow row in gvCustomers.Rows)
		
			    {
		
			        foreach (TableCell cell in row.Cells)
		
			        {
		
			            //Append data with separator.
		
			            sb.Append(cell.Text + ',');
		
			        }
		
			        //Append new line character.
		
			        sb.Append("\r\n");
		
			    }
		
			 
		
			    Response.Output.Write(sb.ToString());
		
			    Response.Flush();
		
			    Response.End();
		
			}
	 
	
		 
	
		VB.Net
	
		
			Protected Sub ExportToCSV(ByVal sender As Object, ByVal e As EventArgs)
		
			    Response.Clear()
		
			    Response.Buffer = True
		
			    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv")
		
			    Response.Charset = ""
		
			    Response.ContentType = "text/csv"
		
			    gvCustomers.AllowPaging = False
		
			    Me.BindGrid()
		
			    Dim sb As StringBuilder = New StringBuilder()
		
			 
		
			    For Each cell As TableCell In gvCustomers.HeaderRow.Cells
		
			        'Append data with separator.
		
			        sb.Append(cell.Text & ",")
		
			    Next
		
			 
		
			    'Append new line character.
		
			    sb.Append(vbCr & vbLf)
		
			 
		
			    For Each row As GridViewRow In gvCustomers.Rows
		
			 
		
			       For Each cell As TableCell In row.Cells
		
			            'Append data with separator.
		
			            sb.Append(cell.Text & ",")
		
			        Next
		
			 
		
			        'Append new line character.
		
			        sb.Append(vbCr & vbLf)
		
			    Next
		
			 
		
			    Response.Output.Write(sb.ToString())
		
			    Response.Flush()
		
			    Response.End()
		
			End Sub
	 
	
		 
	
		 
	
		Error
	
		The following error occurs when you tries to render a control such as GridView to HTML using the RenderControl method.
	
		
			Server Error in '/ASP.Net' Application.
		
			Control gvCustomers of type 'GridView' must be placed inside a form tag with runat=server.
		
		
			Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
			
			Exception Details: System.Web.HttpException: Control 'gvCustomers ' of type 'GridView' must be placed inside a form tag with runat=server.
	 
	
		 
	
		 
	
		Solution
	
		The solution to this problem is to override VerifyRenderingInServerForm event handler.
	
	
		 
	
		 
	
		Screenshots
	
		GridView with Paging enabled
	
	
		 
	
		Exported Word Document
	
	
		 
	
		Exported Excel file
	
	
		 
	
		Exported PDF file
	
	
		 
	
		Exported CSV (Text) file
	
	
		 
	
		 
	
		Demo
	
	
		 
	
		 
	
		Downloads