Home Asp.net Export GridView Data to Word Excel Text Pdf File in Asp.net C#...

Export GridView Data to Word Excel Text Pdf File in Asp.net C# Vb

13
11

In my previous tutorials, I’d explained export only gridview selected row data to word excel text pdf, insert update delete using gridview, print gridview data on print button click and other more cracking tutorials on GridView, Asp.net here.

Now here in this tutorial, I’ll explain how to export gridview data with gridview’s exact CSS style and format to word, excel, pdf (using itextsharp.dll) and text file in asp.net using c# as well as vb.net with example code.

To explain further about how to export gridview data in asp.net, we need to create database table to read data and bind retrieved resultset to gridview, so simply execute following script to sql query editor to create database table and then add few records manually or download complete example code with script at the end of the page.

Here is the script to create “œSubjectDetails” table:

CREATE TABLE [dbo].[SubjectDetails]
(
[SubjectId] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[SubjectName] [nvarchar](100) NULL,
[Marks] [int] NULL,
[Grade] [nvarchar](50) NULL
)

I guess you all know about how to bind gridview. So I’m skipping that point and come to the subject to export gridview data to word, excel, csv, pdf and text file. Following is the HTML Markup that contains asp.net buttons and gridview, simply copy and paste to your .aspx page:

Export GridView Data In Asp.net – [.aspx]

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
<title>Export GridView Data to Word, Excel, CSV, Pdf, Text File In Asp.net</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<table>
<tr>
<td colspan=”3″>
<h4>Export Grid Data to Word, Excel, CSV, Pdf File Examples</h4>
</td>
</tr>
<tr>
<td colspan=”3″>
<asp:Button ID=”btnExportToWord” runat=”server” Text=”ExportToWord”
OnClick=”btnExportToWord_Click” />&nbsp;&nbsp;
<asp:Button ID=”btnExportToExcel” runat=”server” Text=”ExportToExcel”
OnClick=”btnExportToExcel_Click” />&nbsp;&nbsp;
<asp:Button ID=”btnExportToCSV” runat=”server” Text=”ExportToCSV”
OnClick=”btnExportToCSV_Click” />&nbsp;&nbsp;
<asp:Button ID=”btnExportToText” runat=”server” Text=”ExportToText”
OnClick=”btnExportToText_Click” />&nbsp;&nbsp;
<asp:Button ID=”btnExportToPdf” runat=”server” Text=”ExportToPdf”
OnClick=”btnExportToPdf_Click” />
</td>
</tr>
<tr>
<td colspan=”3″>
<asp:GridView ID=”grdResultDetails” runat=”server” AutoGenerateColumns=”false”
PageSize=”5″ AllowPaging=”true”
OnPageIndexChanging=”grdResultDetails_PageIndexChanging”>
<HeaderStyle BackColor=”#9a9a9a” ForeColor=”White” Font-Bold=”true” Height=”30″ />
<PagerStyle HorizontalAlign=”Center” />
<AlternatingRowStyle BackColor=”#f5f5f5″ />
<Columns>
<asp:BoundField DataField=”SubjectName” HeaderText=”SubjectName”
ItemStyle-HorizontalAlign=”Center” ItemStyle-Width=”200″ />
<asp:BoundField DataField=”Marks” HeaderText=”Marks”
ItemStyle-HorizontalAlign=”Center” ItemStyle-Width=”200″ />
<asp:BoundField DataField=”Grade” HeaderText=”Grade”
ItemStyle-HorizontalAlign=”Center” ItemStyle-Width=”200″ />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

After copying HTML Markup, now it’s time to add required .dll and namespace references to code-behind file. To add reference to your project Right Click on References > Add New Reference > Browse to itextsharp.dll > OK.

Note: We need itextsharp.dll to export data to Pdf file (only requires for pdf export, if you don’t want export to pdf functionality, then simply ignore itextsharp.dll and remove reference from the sample project).I already added itextsharp.dll in my sample code. If you want to get more details about itextsharp.dll, visit itextsharp official site here.

After adding the reference, choose a required language (C# or Vb.net), and then copy paste the following code to your code-behind file.

Export GridView Data To Word, Excel, Csv, Text, Pdf In C#

First add the following namespaces to your .cs page:

using System.Data;
using System.IO;
using System.Text;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Data.SqlClient;

Then add the following code snippet to your code-behind file which helps you to export gridview data:

//1st Method: To Export to Word, Excel file
private void ExportFile(string fileName, string contentType)
{
//disable paging to export all data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = false;
LoadGridData();

Response.ClearContent();
Response.Buffer = true;
Response.AddHeader(“content-disposition”, string.Format(“attachment; filename={0}”, fileName));
Response.ContentType = contentType;
StringWriter objSW = new StringWriter();
HtmlTextWriter objTW = new HtmlTextWriter(objSW);
grdResultDetails.RenderControl(objTW);
Response.Write(objSW);
Response.End();
}

//2nd Method: To Export to CSV, Text file
private void ExportTextBasedFile(string fileName, string contentType)
{
//disable paging to export all data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = false;
LoadGridData();

Response.ClearContent();
Response.AddHeader(“content-disposition”, string.Format(“attachment; filename={0}”, fileName));
Response.ContentType = contentType;
StringBuilder objSB = new StringBuilder();
for (int i = 0; i < grdResultDetails.Columns.Count; i++)
{
objSB.Append(grdResultDetails.Columns[i].HeaderText + ‘,’);
}
objSB.Append(“\n”);
for (int j = 0; j < grdResultDetails.Rows.Count; j++)
{
for (int k = 0; k < grdResultDetails.Columns.Count; k++)
{
objSB.Append(grdResultDetails.Rows[j].Cells[k].Text + ‘,’);
}
objSB.Append(“\n”);
}
Response.Write(objSB.ToString());
Response.End();
}

And call them on specific button click event as follows:

//Method for Export to Word
protected void btnExportToWord_Click(object sender, EventArgs e)
{
string fileName = “ExportToWord_” + DateTime.Now.ToShortDateString() + “.doc”,
contentType = “application/ms-word”;

//call 1st export method with fileName and contentType
ExportFile(fileName, contentType);
}

//Method for Export to Excel
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
string fileName = “ExportToExcel_” + DateTime.Now.ToShortDateString() + “.xls”,
contentType = “application/vnd.ms-excel”;

//call 1st export method with fileName and contentType
ExportFile(fileName, contentType);
}

/* Method for Export to CSV
* Note: CSV file is a text representation so we can’t style .csv document*/
protected void btnExportToCSV_Click(object sender, EventArgs e)
{
string fileName = “ExportToCSV_” + DateTime.Now.ToShortDateString() + “.csv”,
contentType = “application/text”;

//call 2nd export method with fileName and contentType
ExportTextBasedFile(fileName, contentType);
}

/* Method for Export to Text
* Note: TEXT file is a text representation so we can’t style .txt document*/
protected void btnExportToText_Click(object sender, EventArgs e)
{
string fileName = “ExportToText_” + DateTime.Now.ToShortDateString() + “.txt”,
contentType = “application/text”;

//call 2nd export method with fileName and contentType
ExportTextBasedFile(fileName, contentType);
}

Following is the method to export data to pdf file:

//Method for Export to PDF
protected void btnExportToPdf_Click(object sender, EventArgs e)
{
//disable paging to export all data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = false;
LoadGridData();

string fileName = “ExportToPdf_” + DateTime.Now.ToShortDateString();
Response.ContentType = “application/pdf”;
Response.AddHeader(“content-disposition”, string.Format(“attachment; filename={0}”,
fileName + “.pdf”));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter objSW = new StringWriter();
HtmlTextWriter objTW = new HtmlTextWriter(objSW);
grdResultDetails.RenderControl(objTW);
StringReader objSR = new StringReader(objSW.ToString());
Document objPDF = new Document(PageSize.A4, 100f, 100f, 100f, 100f);
HTMLWorker objHW = new HTMLWorker(objPDF);
PdfWriter.GetInstance(objPDF, Response.OutputStream);
objPDF.Open();
objHW.Parse(objSR);
objPDF.Close();
Response.Write(objPDF);
Response.End();
}

Export GridView Data To Word, Excel, Csv, Text, Pdf In Vb.net

First add the following namespaces to your .vb page:

Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
Imports System.Data.SqlClient

Then add the following code snippet to your code-behind file which helps you to export gridview data:

‘1st Method: To Export to Word, Excel file
Private Sub ExportFile(ByVal fileName As String, ByVal contentType As String)
‘disable paging to export all data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = False
LoadGridData()

Response.ClearContent()
Response.Buffer = True
Response.AddHeader(“content-disposition”, String.Format(“attachment; filename={0}”, fileName))
Response.ContentType = contentType
Dim objSW As New StringWriter()
Dim objTW As New HtmlTextWriter(objSW)
grdResultDetails.RenderControl(objTW)
Response.Write(objSW)
Response.End()
End Sub

‘2nd Method: To Export to CSV, Text file
Private Sub ExportTextBasedFile(ByVal fileName As String, ByVal contentType As String)
‘disable paging to export all data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = False
LoadGridData()

Response.ClearContent()
Response.AddHeader(“content-disposition”, String.Format(“attachment; filename={0}”, fileName))
Response.ContentType = contentType
Dim objSB As New StringBuilder()
For i As Integer = 0 To grdResultDetails.Columns.Count – 1
objSB.Append(grdResultDetails.Columns(i).HeaderText & AscW(“,”c))
Next i
objSB.Append(ControlChars.Lf)
For j As Integer = 0 To grdResultDetails.Rows.Count – 1
For k As Integer = 0 To grdResultDetails.Columns.Count – 1
objSB.Append(grdResultDetails.Rows(j).Cells(k).Text & “,”c)
Next k
objSB.Append(ControlChars.Lf)
Next j
Response.Write(objSB.ToString())
Response.End()
End Sub

And call them on specific button click event as follows:

‘Method for Export to Word
Protected Sub btnExportToWord_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = “ExportToWord_” & Date.Now.ToShortDateString() & “.doc”,
contentType As String = “application/ms-word”

‘call 1st export method with fileName and contentType
ExportFile(fileName, contentType)
End Sub

‘Method for Export to Excel
Protected Sub btnExportToExcel_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = “ExportToExcel_” & Date.Now.ToShortDateString() & “.xls”,
contentType As String = “application/vnd.ms-excel”

‘call 1st export method with fileName and contentType
ExportFile(fileName, contentType)
End Sub

‘Method for Export to CSV
‘Note: CSV file is a text representation so we can’t style .csv document
Protected Sub btnExportToCSV_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = “ExportToCSV_” & Date.Now.ToShortDateString() & “.csv”,
contentType As String = “application/text”

‘call 2nd export method with fileName and contentType
ExportTextBasedFile(fileName, contentType)
End Sub

‘Method for Export to Text
‘Note: TEXT file is a text representation so we can’t style .txt document
Protected Sub btnExportToText_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = “ExportToText_” & Date.Now.ToShortDateString() & “.txt”,
contentType As String = “application/text”

‘call 2nd export method with fileName and contentType
ExportTextBasedFile(fileName, contentType)
End Sub

Following is the method to export data to pdf file:

‘Method for Export to PDF
Protected Sub btnExportToPdf_Click(ByVal sender As Object, ByVal e As EventArgs)
‘disable paging to export all data and make sure to bind griddata before begin
grdResultDetails.AllowPaging = False
LoadGridData()

Dim fileName As String = “ExportToPdf_” & Date.Now.ToShortDateString()
Response.ContentType = “application/pdf”
Response.AddHeader(“content-disposition”, String.Format(“attachment; filename={0}”,
fileName & “.pdf”))
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim objSW As New StringWriter()
Dim objTW As New HtmlTextWriter(objSW)
grdResultDetails.RenderControl(objTW)
Dim objSR As New StringReader(objSW.ToString())
Dim objPDF As New Document(PageSize.A4, 100.0F, 100.0F, 100.0F, 100.0F)
Dim objHW As New HTMLWorker(objPDF)
PdfWriter.GetInstance(objPDF, Response.OutputStream)
objPDF.Open()
objHW.Parse(objSR)
objPDF.Close()
Response.Write(objPDF)
Response.End()
End Sub

During Development, I Faced Following Errors:

Control ‘grdResultDetails’ of type ‘GridView’ must be placed inside a form tag with runat=server

Server Error in ‘/’ Application.


Control ‘grdResultDetails’ 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 ‘grdResultDetails’ of type ‘GridView’
must be placed inside a form tag with runat=server.

To resolve this issue, please check how to solve control ‘grdResultDetails’ of type ‘GridView’ must be placed inside a form tag with runat=server.

RegisterForEventValidation can only be called during Render();

Server Error in ‘/’ Application.


RegisterForEventValidation can only be called during Render();

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.InvalidOperationException: RegisterForEventValidation can only be
called during Render();

To resolve this issue, please check how to solve RegisterForEventValidation can only be called during Render();.

Example Result

Export gridview data to word, excel, text, pdf file in asp.net c# vb.net

Download Sample Code

[wpdm_package id=’5435′]

11 COMMENTS

  1. Your code works perfectly in a AspNet website.

    I want to do exactly the same in a windows form i.e. export from a DataGridView (Windows forms have only a DataGridView, not GridView) to Word PDF Excel etc.

    Windows forms do not have the Response object so I have not worked out a way to convert your code from ASP.Net to Windows code.

    Can it be done?

    PaulG

    • Hi Paul,

      Thanks.

      No, you can’t convert that way. Unfortunately, I have no idea about windows apps as I’m working on web apps only. Though you can get many tutorials from Google. Good Luck!

  2. Hi,

    I’m getting the following error. Please help

    Unable to cast object of type ‘iTextSharp.text.html.simpleparser.CellWrapper’ to type ‘iTextSharp.text.Paragraph’.

  3. Hi,

    I am doing a application that will execute a store procedure and display query result in excel or PDF.
    How can i used a web form (Textbox and Button) to execute a store procedure and display database result to excel or PDF.

    Best Regards,
    Augustine

  4. Lots of great work here … thanks.
    Export to Excel generates “The file format and extension don’t match. The file could be corrupt or unsafe” on opening in Excel. Any way around that?
    Thanks

  5. Hi,
    Lots of good work here … thanks!
    Export to Excel generates “The file format and extension don’t match. The file could be corrupted of unsafe.” on opening with Excel. Any way around that?
    Thanks.

LEAVE A REPLY

Please enter your comment!
Please enter your name here
Captcha verification failed!
CAPTCHA user score failed. Please contact us!