Introduction
In this article, I will demonstrate how to export GridView data into Word, Excel, and pdf files using ASP.NET.
I will use the jQuery plugin to search, sort, and paginate the data.
Step 1
Open SQL Server 2014 and create a database table.
- CREATE TABLE [dbo].[EmployeeList](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [Name] [nvarchar](50) NULL,
- [Position] [nvarchar](50) NULL,
- [Office] [nvarchar](50) NULL,
- [Age] [int] NULL,
- [Start_Date] [nvarchar](50) NULL,
- [Salary] [nvarchar](50) NULL,
- CONSTRAINT [PK_EmployeeList] PRIMARY KEY CLUSTERED
- (
- [ID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
- Create procedure [dbo].[spGetAllEmployeeList]
- as
- begin
- select ID,Name,Position,Office,Age,Start_Date,Salary from [dbo].[EmployeeList]
- end
Step 2
Open Visual Studio 2015 and click on New Project
Screenshot-1
After clicking on New Project, one window will appear. Select Web from the left panel to choose ASP.NET Web Application, give a meaningful name to your project, then click OK.
After clicking on OK, one more window will appear. Choose Empty check on Web Forms checkbox and click on OK, as shown in the below screenshot.
After clicking on OK, the project will get created with the name as ExportWordExcelAndPDF_Demo.
Step 3
Right-click on web config file to add the database connection.
- <connectionStrings>
- <add name="DBCS" connectionString="data source=DESKTOP-M021QJH\SQLEXPRESS; database=SampleDB; integrated security=true;"/>
- </connectionStrings>
Step 4
Right-click on the project on Solution Explorer, select Add, choose New Item, and click on it.
Screenshot-1
Another window will appear. Select web from the left panel and choose Web Form, give it a meaningful name and click on Add. The Web Form will be added to the project.
Screenshot-2
Step 5
Click on Tools >> NuGet Package Manager >> Manage NuGet Packages for Solution.
Screenshot for NuGet Package
After that, a window will appear. Choose Browse >> type bootstrap and install the relevant package from the list.
Similarly, type jQuery and install the latest version of jQuery package in your project along with the jQuery validation file from NuGet and then, close the NuGet Solution.
Keep the required bootstrap and jQuery files while delete the remaining files if not using. Or you can download from and add in project.
Step 6
Add the following styles and scripts in head section of the Web Form.
- <link href="Content/bootstrap.min.css" rel="stylesheet" />
- <script src="scripts/jquery-3.3.1.min.js"></script>
- <script src="scripts/bootstrap.min.js"></script>
- <link href="Content/dataTables.bootstrap4.min.css" rel="stylesheet" />
- <script src="scripts/dataTables.bootstrap4.min.js"></script>
- <script src="scripts/jquery.dataTables.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- $("#EmployeeGridViewList").prepend($("<thead></thead>").append($(this).find("tr:first"))).dataTable();
- });
- </script>
- <style>
- .btnMargin {
- margin-bottom: 10px !important;
- }
- </style>
Step 7
Design the Web Form using HTML, Bootstrap, and ASP.NET buttons and GridView control.
- <body>
- <form id="form1" runat="server">
- <div class="container py-4">
- <h5 class="text-uppercase text-center">How to export gridview data in word,excel and Pdf format using asp.net</h5>
- <div class="card">
- <div class="card-header bg-primary text-white">
- <h5 class="card-title text-uppercase">Employees List</h5>
- </div>
- <div class="card-body">
- <asp:Button ID="btnExportToWord" CssClass="btnMargin btn btn-outline-primary rounded-0" runat="server" Text="ExportToWord" OnClick="btnExportToWord_Click" />
- <asp:Button ID="btnExportToExcel" CssClass="btnMargin btn btn-outline-primary rounded-0" runat="server" Text="ExportToExcel" OnClick="btnExportToExcel_Click" />
- <asp:Button ID="btnExportToPDF" CssClass="btnMargin btn btn-outline-primary rounded-0" runat="server" Text="ExportToPDF" OnClick="btnExportToPDF_Click" />
- <asp:GridView ID="EmployeeGridViewList" CssClass="table table-bordered" runat="server"></asp:GridView>
- </div>
- </div>
- </div>
- </form>
- </body>
Step 8
Right-click on Web Form, select view code, and click on it.
Add namespace
- using System;
- using System.IO;
- using System.Web.UI;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using System.Web;
- using iTextSharp.text;
- using iTextSharp.text.html.simpleparser;
- using iTextSharp.text.pdf;
Bind GridView with the database
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindGridView();
- }
- }
-
- private void BindGridView()
- {
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetAllEmployeeList", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- EmployeeGridViewList.DataSource = cmd.ExecuteReader();
- EmployeeGridViewList.DataBind();
- }
- }
Add the following method to export Word and Excel format.
- public override void VerifyRenderingInServerForm(Control control)
- {
- }
Step 9
Double click on ExportToWord control. Write the following code.
- protected void btnExportToWord_Click(object sender, EventArgs e)
- {
- Response.ClearContent();
- Response.AppendHeader("content-disposition", "attachment; filename=Employees.doc");
- Response.ContentType = "application/word";
- StringWriter stringWriter = new StringWriter();
- HtmlTextWriter htw = new HtmlTextWriter(stringWriter);
- EmployeeGridViewList.HeaderRow.Style.Add("background-color", "#FFFFFF");
- EmployeeGridViewList.RenderControl(htw);
- Response.Write(stringWriter.ToString());
- Response.End();
- }
Step 10
Double click on ExportToExcel control. Write the following code.
- protected void btnExportToExcel_Click(object sender, EventArgs e)
- {
- Response.ClearContent();
- Response.AppendHeader("content-disposition", "attachment; filename=Employees.xls");
- Response.ContentType = "application/excel";
- StringWriter stringWriter = new StringWriter();
- HtmlTextWriter htw = new HtmlTextWriter(stringWriter);
- EmployeeGridViewList.HeaderRow.Style.Add("background-color", "#FFFFFF");
- EmployeeGridViewList.RenderControl(htw);
- Response.Write(stringWriter.ToString());
- Response.End();
- }
Step 11
Double-click on ExportToPDF control. Write the following code. To export the PDF format, we need to add itextsharp.dll from here - https://sourceforge.net/projects/itextsharp/
- protected void btnExportToPDF_Click(object sender, EventArgs e)
- {
- Response.ContentType = "application/pdf";
- Response.AddHeader("content-disposition","attachment;filename=Employees.pdf");
- Response.Cache.SetCacheability(HttpCacheability.NoCache);
- StringWriter sw = new StringWriter();
- HtmlTextWriter hw = new HtmlTextWriter(sw);
- EmployeeGridViewList.RenderControl(hw);
- StringReader sr = new StringReader(sw.ToString());
- Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
- #pragma warning disable CS0612 // Type or member is obsolete
- HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
- #pragma warning restore CS0612 // Type or member is obsolete
- PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
- pdfDoc.Open();
- htmlparser.Parse(sr);
- pdfDoc.Close();
- Response.Write(pdfDoc);
- Response.End();
- EmployeeGridViewList.AllowPaging = true;
- EmployeeGridViewList.DataBind();
- }
Complete code of Web Form
- using System;
- using System.IO;
- using System.Web.UI;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using System.Web;
- using iTextSharp.text;
- using iTextSharp.text.html.simpleparser;
- using iTextSharp.text.pdf;
-
- namespace ExportWordExcelCSVAndPDF_Demo
- {
- public partial class EmployeesList : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindGridView();
- }
- }
-
- private void BindGridView()
- {
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetAllEmployeeList", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- EmployeeGridViewList.DataSource = cmd.ExecuteReader();
- EmployeeGridViewList.DataBind();
- }
- }
-
- protected void btnExportToWord_Click(object sender, EventArgs e)
- {
- Response.ClearContent();
- Response.AppendHeader("content-disposition", "attachment; filename=Employees.doc");
- Response.ContentType = "application/word";
- StringWriter stringWriter = new StringWriter();
- HtmlTextWriter htw = new HtmlTextWriter(stringWriter);
- EmployeeGridViewList.HeaderRow.Style.Add("background-color", "#FFFFFF");
- EmployeeGridViewList.RenderControl(htw);
- Response.Write(stringWriter.ToString());
- Response.End();
- }
-
- protected void btnExportToExcel_Click(object sender, EventArgs e)
- {
- Response.ClearContent();
- Response.AppendHeader("content-disposition", "attachment; filename=Employees.xls");
- Response.ContentType = "application/excel";
- StringWriter stringWriter = new StringWriter();
- HtmlTextWriter htw = new HtmlTextWriter(stringWriter);
- EmployeeGridViewList.HeaderRow.Style.Add("background-color", "#FFFFFF");
- EmployeeGridViewList.RenderControl(htw);
- Response.Write(stringWriter.ToString());
- Response.End();
- }
-
- public override void VerifyRenderingInServerForm(Control control)
- {
-
- }
-
- protected void btnExportToPDF_Click(object sender, EventArgs e)
- {
- Response.ContentType = "application/pdf";
- Response.AddHeader("content-disposition","attachment;filename=Employees.pdf");
- Response.Cache.SetCacheability(HttpCacheability.NoCache);
- StringWriter sw = new StringWriter();
- HtmlTextWriter hw = new HtmlTextWriter(sw);
- EmployeeGridViewList.RenderControl(hw);
- StringReader sr = new StringReader(sw.ToString());
- Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
- #pragma warning disable CS0612 // Type or member is obsolete
- HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
- #pragma warning restore CS0612 // Type or member is obsolete
- PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
- pdfDoc.Open();
- htmlparser.Parse(sr);
- pdfDoc.Close();
- Response.Write(pdfDoc);
- Response.End();
- EmployeeGridViewList.AllowPaging = true;
- EmployeeGridViewList.DataBind();
- }
- }
- }
Step 12
Run the project by pressing Ctrl+F5.
Conclusion
In this article, I have explained how to export GridView data into Word, Excel and PDF step by step.
I hope it will be helpful.