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 DataSet or DataTable to Word Excel PDF and CSV Formats
Author Name: Mudassar Khan Published Date: May 20, 2009
Filed Under :
ASP.Net
 |
Excel
 |
GridView
Views: 13944

On many occasion there’s a need to export dataset or datatable to Word, Excel, PDF or CSV (Text) formats. In this article I am explaining how to achieve the same in ASP.Net.

To export GridView to Word, Excel, PDF or CSV (Text) refer my article Export GridView To Word/Excel/PDF/CSV in ASP.Net

 

For this tutorial I am using NorthWind Database which can be downloaded from here

Once that is downloaded you can attach the same to your SQL Server.

 

Connection String

Below is my connection string to the database.

<add name="conString" connectionString="Data Source=.\SQLEXPRESS;

                    database=Northwind;Integrated Security=true"/>

 

Namespaces

C#

using System.Data;

using System.Data.SqlClient;

using System.Text;

using System.IO;

using iTextSharp.text;

using iTextSharp.text.pdf;

using iTextSharp.text.html;

using iTextSharp.text.html.simpleparser;

 

VB.Net

Imports System.Data

Imports System.Data.SqlClient

Imports System.Text

Imports System.IO

Imports iTextSharp.text

Imports iTextSharp.text.pdf

Imports iTextSharp.text.html

Imports iTextSharp.text.html.simpleparser

 

  

 

Function to get the results in datatable

 

Next I am using my very own GetData function to get the desired data from the database which is given below.

C#

private DataTable GetData(SqlCommand cmd)

{

    DataTable dt = new DataTable();

    String strConnString = System.Configuration.ConfigurationManager.

         ConnectionStrings["conString"].ConnectionString;

    SqlConnection con = new SqlConnection(strConnString);

    SqlDataAdapter sda = new SqlDataAdapter();

    cmd.CommandType = CommandType.Text;

    cmd.Connection = con;

    try

    {

        con.Open();

        sda.SelectCommand = cmd;

        sda.Fill(dt);

        return dt;

    }

    catch (Exception ex)

    {

        throw ex;

    }

    finally

    {

        con.Close();

        sda.Dispose();

        con.Dispose();

    }

}

 

   

        

VB.Net

Private Function GetData(ByVal cmd As SqlCommand) As DataTable

    Dim dt As New DataTable()

    Dim strConnString As [String] = System.Configuration _

        .ConfigurationManager.ConnectionStrings("conString").ConnectionString

    Dim con As New SqlConnection(strConnString)

    Dim sda As New SqlDataAdapter()

    cmd.CommandType = CommandType.Text

    cmd.Connection = con

    Try

       con.Open()

       sda.SelectCommand = cmd

       sda.Fill(dt)

       Return dt

    Catch ex As Exception

       Throw ex

    Finally

        con.Close()

        sda.Dispose()

        con.Dispose()

    End Try

End Function

 

As you can see above I am passing the query to the GetData function and it returns the results as datatable back. More details on the above function refer my article Parameterized Queries ADO.Net

   

          

Export to Word

 

Below is the code to export the datatable to Word Format. It first fills the datatable using the GetData function and then binds it to a dummy GridView and then the dummy GridView is rendered as Word document.

 

C#

protected void ExportToWord(object sender, EventArgs e)

{

    //Get the data from database into datatable

    string strQuery = "select CustomerID, ContactName, City, PostalCode" +

                      " from customers";

    SqlCommand cmd = new SqlCommand(strQuery);

    DataTable dt = GetData(cmd);

 

    //Create a dummy GridView

    GridView GridView1 = new GridView();

    GridView1.AllowPaging = false;

    GridView1.DataSource = dt;

    GridView1.DataBind();

 

    Response.Clear();

    Response.Buffer = true;

    Response.AddHeader("content-disposition",

        "attachment;filename=DataTable.doc");

    Response.Charset = "";

    Response.ContentType = "application/vnd.ms-word ";

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.RenderControl(hw);

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

    Response.Flush();

    Response.End();

}

 

 

       

VB.Net

Protected Sub ExportToWord(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportWord.Click

   'Get the data from database into datatable

   Dim strQuery As String = "select CustomerID, ContactName, City, " & _

                                 "PostalCode from customers"

   Dim cmd As New SqlCommand(strQuery)

   Dim dt As DataTable = GetData(cmd)

 

   'Create a dummy GridView

   Dim GridView1 As New GridView()

   GridView1.AllowPaging = False

   GridView1.DataSource = dt

   GridView1.DataBind()

 

   Response.Clear()

   Response.Buffer = True

   Response.AddHeader("content-disposition", _

        "attachment;filename=DataTable.doc")

   Response.Charset = ""

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

   Dim sw As New StringWriter()

   Dim hw As New HtmlTextWriter(sw)

   GridView1.RenderControl(hw)

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

   Response.Flush()

   Response.End()

End Sub

 

The figure below displays the generated Microsoft Word Document.



Exported Word Document



Export to Excel

 

Below is the code to export the datatable to Excel Format. It first fills the datatable using the GetData function and then binds it to a dummy GridView and then the dummy GridView is rendered as Excel Workbook. Also you will notice I applied textmode style to all the rows so that it in rendered as text.

 

C#

protected void ExportToExcel(object sender, EventArgs e)

{

    //Get the data from database into datatable

    string strQuery = "select CustomerID, ContactName, City, PostalCode" +

        " from customers";

    SqlCommand cmd = new SqlCommand(strQuery);

    DataTable dt = GetData(cmd);

 

    //Create a dummy GridView

    GridView GridView1 = new GridView();

    GridView1.AllowPaging = false;

    GridView1.DataSource = dt;

    GridView1.DataBind();

 

    Response.Clear();

    Response.Buffer = true;

    Response.AddHeader("content-disposition",

     "attachment;filename=DataTable.xls");

    Response.Charset = "";

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

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

 

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

    {

        //Apply text style to each Row

        GridView1.Rows[i].Attributes.Add("class", "textmode");

    }

    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 ExportToExcel(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportExcel.Click

     'Get the data from database into datatable

     Dim strQuery As String = "select CustomerID, ContactName, City, " & _

                                 "PostalCode from customers"

     Dim cmd As New SqlCommand(strQuery)

     Dim dt As DataTable = GetData(cmd)

 

     'Create a dummy GridView

     Dim GridView1 As New GridView()

     GridView1.AllowPaging = False

     GridView1.DataSource = dt

     GridView1.DataBind()

 

     Response.Clear()

     Response.Buffer = True

     Response.AddHeader("content-disposition", _

          "attachment;filename=DataTable.xls")

     Response.Charset = ""

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

     Dim sw As New StringWriter()

     Dim hw As New HtmlTextWriter(sw)

 

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

       'Apply text style to each Row

        GridView1.Rows(i).Attributes.Add("class", "textmode")

     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 figure below displays the generated Microsoft Excel Sheet.



Exported Excel Document



Export to Portable Document Format (PDF)

      

 

Below is the code to export the datatable to PDF Format. It first fills the datatable using the GetData function and then binds it to a dummy GridView and then the dummy GridView is rendered as PDF document using the iTextSharp Library which is a free open source library and can be downloaded from here

.

C#

protected void ExportToPDF(object sender, EventArgs e)

{

    //Get the data from database into datatable

    string strQuery = "select CustomerID, ContactName, City, PostalCode" +

        " from customers";

    SqlCommand cmd = new SqlCommand(strQuery);

    DataTable dt = GetData(cmd);

 

    //Create a dummy GridView

    GridView GridView1 = new GridView();

    GridView1.AllowPaging = false;

    GridView1.DataSource = dt;

    GridView1.DataBind();

 

    Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition",

        "attachment;filename=DataTable.pdf");

    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    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 ExportToPDF(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportPDF.Click

    'Get the data from database into datatable

    Dim strQuery As String = "select CustomerID, ContactName, City," _

            & " PostalCode from customers"

    Dim cmd As New SqlCommand(strQuery)

    Dim dt As DataTable = GetData(cmd)

 

        'Create a dummy GridView

    Dim GridView1 As New GridView()

    GridView1.AllowPaging = False

    GridView1.DataSource = dt

    GridView1.DataBind()

 

    Response.ContentType = "application/pdf"

    Response.AddHeader("content-disposition", _

           "attachment;filename=DataTable.pdf")

    Response.Cache.SetCacheability(HttpCacheability.NoCache)

    Dim sw As New StringWriter()

    Dim hw As New HtmlTextWriter(sw)

    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 figure below displays the generated PDF Document.



Exported PDF Document



Export to Comma Separated Values (CSV)

 

Below is the code to export the datatable to CSV or Text Format. It first fills the datatable using the GetData function. To export dataset to CSV there is no need of dummy GridView. We just have to loop through the records and append the delimiting character comma.

 

C#

protected void ExportToCSV(object sender, EventArgs e)

{

    //Get the data from database into datatable

    string strQuery = "select CustomerID, ContactName, City, PostalCode" +

         " from customers";

    SqlCommand cmd = new SqlCommand(strQuery);

    DataTable dt = GetData(cmd);

 

    Response.Clear();

    Response.Buffer = true;

    Response.AddHeader("content-disposition",

        "attachment;filename=DataTable.csv");

    Response.Charset = "";

    Response.ContentType = "application/text";

 

 

    StringBuilder sb = new StringBuilder();

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

    {

        //add separator

        sb.Append(dt.Columns[k].ColumnName + ',');

    }

    //append new line

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

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

    {

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

        {

            //add separator

            sb.Append(dt.Rows[i][k].ToString().Replace(",", ";") + ',');

        }

        //append new line

        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 System.EventArgs) Handles btnExportCSV.Click

   'Get the data from database into datatable

   Dim strQuery As String = "select CustomerID, ContactName, City," & _

           " PostalCode from customers"

   Dim cmd As New SqlCommand(strQuery)

   Dim dt As DataTable = GetData(cmd)

 

   Response.Clear()

   Response.Buffer = True

   Response.AddHeader("content-disposition", _

           "attachment;filename=DataTable.csv")

   Response.Charset = ""

   Response.ContentType = "application/text"

 

   Dim sb As New StringBuilder()

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

        'add separator

         sb.Append(dt.Columns(k).ColumnName + ","c)

   Next

   'append new line

   sb.Append(vbCr & vbLf)

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

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

        'add separator

         sb.Append(dt.Rows(i)(k).ToString().Replace(",", ";") + ","c)

      Next

     'append new line

      sb.Append(vbCr & vbLf)

   Next

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

   Response.Flush()

   Response.End()

End Sub

 

The figure below displays the generated CSV File.



Exported CSV File



This completes the article. You can download the code in VB.Net and C# using the link below

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

Kalu Nsi said:
Thank you so much. It works like magic.
January 14, 2010  

valamas said:
Thank you very much
February 03, 2010  

Jay said:
At first let me thank you for the wonderful and the smartest way this article has been written.br br Well I have a little different situation i.e. I have two datatables in the dataset that I want to export to excel. With one data table it works fine but if try to call the ExportToExcel function with 2 datatables it takes long time and exports only first datatable.br br Im using Asp.Net 3.5 with C#.br br Any help at the earliest will be greatly appreciated.br br Thanks
March 03, 2010  

Mudassar Khan said:
Reply To: Jay
You can check my article where I explained how to export multiple grids
http://www.aspsnippets.com/Articles/Exporting-Multiple-GridViews-To-Excel-SpreadSheet-in-ASP.Net.aspx
March 04, 2010  

ashish kumar sharma said:
Hibr really its wonderfull....br can we fomat pdf document according to our need plz reply me.......i need urgent
March 09, 2010  

Mudassar Khan said:
Reply To: ashish kumar sharma
All the information you'll get here
http://itextsharp.sourceforge.net/tutorial/index.html
March 10, 2010  

Geraldine Underhay said:
Thank you so much Ive been looking for one that actually works for weeks.
April 13, 2010  

Dan Cawley said:
Most excellent I plan to run wild with little gem
April 15, 2010  

srinivas said:
Article is very good but you are using gridview for binding data and then you are exporting. But i want to export datatable directly to wordexcelpdfcsv is it possible. If so please give me the solution.br br Thank you very much once again for ur article
April 21, 2010  

Mudassar Khan said:
Reply To: srinivas
No without GridView iy is not possible. For directly export you will then make use if Interop Excel library
April 21, 2010  

ramarao said:
I wonder by looking at ur code...ur code realy helped me ....i never ever forgot about ur help...thanks a lot manbr br Thanks br Ram
May 13, 2010  

Jeenu said:
Thank u for such a code .br But when i export to excel my bit fields are getting as checkbox in excel plz send me the code for getting those as True False value br .br Urgent
May 27, 2010  

Mudassar Khan said:
Reply To: Jeenu
You will need to remove the checkboxes before export by setting visible = false
May 29, 2010  

Gnanadesigan said:
hai Madussar it works finehow to export the data table to excel without using the Gridview. if i click the button means it will show the excel filecan u help me ....Urgent..br
June 08, 2010  

Mudassar Khan said:
Reply To: Gnanadesigan
Without Gridview its only possible with Interop Excel library
June 11, 2010  

Tim said:
Is there a maximum size limit using this method Do you know any way to increase the size limit
June 12, 2010  

Rjay said:
Hi Im trying your code to export to pdf but seems like Im having problem to several items that says not defined. br Items are DocumentHTMLWorker and PdfWriter. I already added all imports but problem persist. What did I missbr br Im using asp.net 2.0 vb code.br Thanks in advancebr RJ
June 13, 2010  

gnanadesigank said:
Hai mudassarits working fine in export to excel in offie 2003 but the same thing im export the datatable to excel 2007 means it will display the following waring Message and then click ok means it will open the excel file..that warning Message is.......THE FILE YOU TRYING TO OPENSTATUS MASTER REPORT1.XLSIS IN A DIFFERENT FORMATTHAN SPECIFIED BU THE FILE EXTENSION.VERIFY THAT THE FILE IS NOT CORRUPTED AND IS FORM A TRUSTED SOURCE BEFORE OPENING THE FILE.DO U WANT TO OPEN THE FILE NOW....Is It any way to correct this warning message..give me ur suggestion soon as possible(urgent)br br thank Youbr
June 16, 2010  

Mudassar Khan said:
Reply To: gnanadesigank
Ignore that warning. That's something issue in Excel you cannot stop it from ASP.Net
June 18, 2010  

Mudassar Khan said:
Reply To: Rjay
Make sure you added all namespaces. Download the sample for reference
June 18, 2010  

Mudassar Khan said:
Reply To: Tim
There is no limit as such.
June 18, 2010  

abhishek said:
wat are these directories how can i include it in my .Net code br br M getting type or namespace could not found errorbr plz help.br br using iTextSharp.textbr using iTextSharp.text.pdfbr using iTextSharp.text.htmlbr using iTextSharp.text.html.simpleparserbr
June 21, 2010  

Mudassar Khan said:
Reply To: abhishek
Please download the sample and refer it
June 24, 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