ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Export GridView To Word Excel PDF CSV Formats in ASP.Net
Author Name: Mudassar Khan Published Date: March 14, 2009
Filed Under :
ASP.Net
 |
Excel
 |
GridView
Views: 30887

In this article, I will explain how to export GridView to Word, Excel, PDF and CSV formats.

Exporting to Word, Excel and CSV can be easily achieved using ASP.Net without any third party tools, but for exporting GridView to PDF I am using iTextSharp which is a free library for exporting html to PDF.

 

To start with I have a GridView in which I am showing Customers records from the NorthWind Database.

The HTML markup of the GridView is as shown below

 

<asp:GridView ID="GridView1" runat="server"

    AutoGenerateColumns = "false" Font-Names = "Arial"

    Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" 

    HeaderStyle-BackColor = "green" AllowPaging ="true"  

    OnPageIndexChanging = "OnPaging" >

   <Columns>

    <asp:BoundField ItemStyle-Width = "150px" DataField = "CustomerID"

    HeaderText = "CustomerID" />

    <asp:BoundField ItemStyle-Width = "150px" DataField = "City"

    HeaderText = "City"/>

    <asp:BoundField ItemStyle-Width = "150px" DataField = "Country"

    HeaderText = "Country"/>

    <asp:BoundField ItemStyle-Width = "150px" DataField = "PostalCode"

    HeaderText = "PostalCode"/>

   </Columns>

</asp:GridView>

 

In the figure below the GridView is shown with four buttons

1.     Export To Word

2.     Export To Excel

3.     Export To PDF

4.     Export To CSV



GridView with Sample Data



Export to Microsoft Word Format

 

C#

protected void btnExportWord_Click(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 ";

    StringWriter sw= new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.AllowPaging = false;

    GridView1.DataBind();

    GridView1.RenderControl(hw);

    Response.Output.Write(sw.ToString());

    Response.Flush();

    Response.End();

}

 

VB.Net

Protected Sub btnExportWord_Click(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 "

        Dim sw As New StringWriter()

        Dim hw As New HtmlTextWriter(sw)

        GridView1.AllowPaging = False

        GridView1.DataBind()

        GridView1.RenderControl(hw)

        Response.Output.Write(sw.ToString())

        Response.Flush()

        Response.End()

    End Sub

 

The above function renders the GridView contents as Microsoft Word format. You will notice I have disabled paging before exporting, so that all the pages are exported.

The Output Exported File



GridView data exported to Word Document



Export to Microsoft Excel Format

 

For exporting the document to Excel if you do it directly as done in case of word the row background color is applied throughout to all the columns in the Excel Sheet hence in order to avoid it. I have done a workaround below.

First I am changing the background color of each row back to white.

Then I am applying the background color to each individual cell rather than the whole row. Thus when you export now you will notice that the formatting is applied only to the GridView cells and not all

Also I am applying textmode style class to all cells and then adding the style CSS class to the GridView before rendering it, this ensures that all the contents of GridView are rendered as text.

 

protected void btnExportExcel_Click(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";

StringWriter sw = new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

 

GridView1.AllowPaging = false;

GridView1.DataBind();

 

//Change the Header Row back to white color

GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");

 

//Apply style to Individual Cells

GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");

GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");

GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");

GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");  

 

for (int i = 0; i < GridView1.Rows.Count;i++ )

{

    GridViewRow row = GridView1.Rows[i];

 

    //Change Color back to white

    row.BackColor = System.Drawing.Color.White;

 

    //Apply text style to each Row

    row.Attributes.Add("class", "textmode");

 

    //Apply style to Individual Cells of Alternating Row

    if (i % 2 != 0)

    {

        row.Cells[0].Style.Add("background-color", "#C2D69B");

        row.Cells[1].Style.Add("background-color", "#C2D69B");

        row.Cells[2].Style.Add("background-color", "#C2D69B");

        row.Cells[3].Style.Add("background-color", "#C2D69B");  

    }

}

GridView1.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 btnExportExcel_Click(ByVal sender As Object,

ByVal e As EventArgs)

  Response.Clear()

  Response.Buffer = True

 

  Response.AddHeader("content-disposition",

  "attachment;filename=GridViewExport.xls")

  Response.Charset = ""

  Response.ContentType = "application/vnd.ms-excel"

 

  Dim sw As New StringWriter()

  Dim hw As New HtmlTextWriter(sw)

 

  GridView1.AllowPaging = False

  GridView1.DataBind()

 

  'Change the Header Row back to white color

  GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF")

 

  'Apply style to Individual Cells

  GridView1.HeaderRow.Cells(0).Style.Add("background-color", "green")

  GridView1.HeaderRow.Cells(1).Style.Add("background-color", "green")

  GridView1.HeaderRow.Cells(2).Style.Add("background-color", "green")

  GridView1.HeaderRow.Cells(3).Style.Add("background-color", "green")

 

  For i As Integer = 0 To GridView1.Rows.Count - 1

   Dim row As GridViewRow = GridView1.Rows(i)

 

   'Change Color back to white

   row.BackColor = System.Drawing.Color.White

 

   'Apply text style to each Row

   row.Attributes.Add("class", "textmode")

 

   'Apply style to Individual Cells of Alternating Row

   If i Mod 2 <> 0 Then

    row.Cells(0).Style.Add("background-color", "#C2D69B")

    row.Cells(1).Style.Add("background-color", "#C2D69B")

    row.Cells(2).Style.Add("background-color", "#C2D69B")

    row.Cells(3).Style.Add("background-color", "#C2D69B")

   End If

  Next

  GridView1.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 Sub

 

The Output Exported File



GridView data exported to Excel Document



Export to Portable Document Format

 

For exporting the GridView to PDF I am using the iTextSharp Library. You will need to Add Reference for the iTextSharp Library in your Website.

Then import the following Namespaces

 

C#

using iTextSharp.text;

using iTextSharp.text.pdf;

using iTextSharp.text.html;

using iTextSharp.text.html.simpleparser;

 

VB.Net

Imports iTextSharp.text

Imports iTextSharp.text.pdf

Imports iTextSharp.text.html

Imports iTextSharp.text.html.simpleparser

 

By default the iTextSharp Library does not support background color of table cells or table rows

Hence when you render it as PDF your GridView is rendered without any formatting.

Recently I read an article on hamang.net where the author has provided the snippet to modify the iTextSharp so that it exports the HTML with background color.

 

For this tutorial, I have already modified the iTextSharp Library DLL so that the GridView is rendered with all the background color used. You can refer the code for exporting GridView to PDF below

 

              

C#

protected void btnExportPDF_Click(object sender, EventArgs e)

{

    Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition",

     "attachment;filename=GridViewExport.pdf");

    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.AllowPaging = false;

    GridView1.DataBind();

    GridView1.RenderControl(hw);

    StringReader sr = new StringReader(sw.ToString());

    Document pdfDoc = new Document(PageSize.A4, 10f,10f,10f,0f);

    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();

    htmlparser.Parse(sr);

    pdfDoc.Close();

    Response.Write(pdfDoc);

    Response.End(); 

}

 

VB.Net

Protected Sub btnExportPDF_Click(ByVal sender As Object,

ByVal e As EventArgs)

 Response.ContentType = "application/pdf"

 Response.AddHeader("content-disposition",

 "attachment;filename=GridViewExport.pdf")

 Response.Cache.SetCacheability(HttpCacheability.NoCache)

 Dim sw As New StringWriter()

 Dim hw As New HtmlTextWriter(sw)

 GridView1.AllowPaging = False

 GridView1.DataBind()

 GridView1.RenderControl(hw)

 Dim sr As New StringReader(sw.ToString())

 Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)

 Dim htmlparser As New HTMLWorker(pdfDoc)

 PdfWriter.GetInstance(pdfDoc, Response.OutputStream)

 pdfDoc.Open()

 htmlparser.Parse(sr)

 pdfDoc.Close()

 Response.Write(pdfDoc)

 Response.End()

End Sub

 

The Output Exported File



GridView data exported to PDF Document



Export to Text/CSV

 

Finally comes exporting GridView to CSV or Text File delimited by a separator like comma.

To export the GridView as CSV, I am running a two for loops. While looping through the GridView columns and appending comma after each column and while looping through rows appending new line character. Refer the code below.

 

C#

protected void btnExportCSV_Click(object sender, EventArgs e)

{

    Response.Clear();

    Response.Buffer = true;

    Response.AddHeader("content-disposition",

     "attachment;filename=GridViewExport.csv");

    Response.Charset = "";

    Response.ContentType = "application/text";

 

    GridView1.AllowPaging = false;

    GridView1.DataBind();

 

    StringBuilder sb = new StringBuilder();

    for (int k = 0; k < GridView1.Columns.Count; k++)

    {

        //add separator

        sb.Append(GridView1.Columns[k].HeaderText + ',');

    }

    //append new line

    sb.Append("\r\n");

    for (int i = 0; i < GridView1.Rows.Count; i++)

    {

        for (int k = 0; k < GridView1.Columns.Count; k++)

        {

            //add separator

            sb.Append(GridView1.Rows[i].Cells[k].Text + ',');

        }

        //append new line

        sb.Append("\r\n");

    }

    Response.Output.Write(sb.ToString());

    Response.Flush();

    Response.End();

}

      

 

VB.Net

Protected Sub btnExportCSV_Click(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 = "application/text"

 

 GridView1.AllowPaging = False

 GridView1.DataBind()

 

 Dim sb As New StringBuilder()

 For k As Integer = 0 To GridView1.Columns.Count - 1

  'add separator

  sb.Append(GridView1.Columns(k).HeaderText + ","c)

 Next

 'append new line

 sb.Append(vbCr & vbLf)

 For i As Integer = 0 To GridView1.Rows.Count - 1

  For k As Integer = 0 To GridView1.Columns.Count - 1

   'add separator

   sb.Append(GridView1.Rows(i).Cells(k).Text + ","c)

  Next

  'append new line

  sb.Append(vbCr & vbLf)

 Next

 Response.Output.Write(sb.ToString())

 Response.Flush()

 Response.End()

End Sub

 

The Output Exported File



GridView data exported to CSV File



When you run the application first time and click export you might receive the following error



Error encountered when you click export



To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.

  

C#

public override void VerifyRenderingInServerForm(Control control)

{

    /* Verifies that the control is rendered */

}

 

VB.Net

Public Overloads Overrides Sub VerifyRenderingInServerForm

(ByVal control As Control)

    ' Verifies that the control is rendered

End Sub

 

This completes the article you can view the live demo here

The source code is available in C# and VB.Net here

 

GridViewExport.zip (1.15 mb)


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

karthi said:
The pdf coversion served my purpose Thank you
January 05, 2010  

duffer said:
but this is exporting whole aspx page on my machine
January 19, 2010  

danis said:
i have an error when use ur coding..can u help me..when i debug there is no error but the button export doesnt work...can u help me plz..br in my code have underline blue at StringWriter and HtmlTextWriter..br when i put this namespace the color on the text become gray and mention it using directive is not required:usingSystem.Web.UI.WebControls.WebPartsbr using System.Web.UI.HtmlControlsbr br br br StringWriter sw new StringWriter()br HtmlTextWriter hw new HtmlTextWriter(sw)
January 19, 2010  

Mudassar Khan said:
Reply To: duffer
That can only happen in cases when your HTML is invalid or incorrect make sure everything is proper and all HTML is well formed
January 20, 2010  

Mudassar Khan said:
Reply To: danis
Try to download the code sample from this site and use the code provided in it
January 20, 2010  

Chamndralekha said:
im getting only table header in the csv file while exporting gridview to csv please help me..
February 05, 2010  

Rahul said:
csv is not comming properly it is not seperated by comma and more over both excel and csv looks same only background colour differes... mudassar u have done a gud job but check this error first.
February 05, 2010  

Mudassar Khan said:
Reply To: Chamndralekha
Hi,
Debug and Check whether Your Gridview has rows in it before export
February 05, 2010  

Mudassar Khan said:
Reply To: Rahul
There is no error. To View commas open the file with notepad instead of MS Excel
February 05, 2010  

anu said:
when i use convert to pdf.i have got an error the document has no pages.
February 14, 2010  

Mudassar Khan said:
Reply To: anu
This means your Grid does not have any rows in it. Bind Gridview before exporting
February 15, 2010  

Noora said:
Thank you Mudassar for this great code and its work fine with me but the question is how can i add a title to the pdf page and make the font smaller i dont want to use a datatable for adding a title is there any other way for adding title
March 02, 2010  

Mudassar Khan said:
Reply To: Noora
hi,
You will need to refer the tutorials of iTextSharp
itextsharp.sourceforge.net/tutorial/index.html
March 02, 2010  

Noora said:
Thank you Mudassar for this great code and its work fine with me but the question is how can i add a title to the pdf page and make the font smaller i dont want to use a datatable for adding a title is there any other way for adding title
March 02, 2010  

Mudassar Khan said:
Reply To: Noora
For that you will need to use the elements of iTextSharp
http://itextsharp.sourceforge.net/tutorial/ch01.html
March 04, 2010  

alok aggarwal said:
hi sir br br a great piece of code for gridviewbr but it failed in gridview paging.br please tell how to copy the whole data till end page if paging in enabled in gridview.br br ill be highly grateful to you for your help.br br kind regardsbr alok aggarwal
March 09, 2010  

Mudassar Khan said:
Reply To: alok aggarwal
Hi,

The above code exports all the rows

GridView1.AllowPaging = false;

I have set this before exporting check above Else download the sample
March 10, 2010  

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code