Introduction
A Grid View is a graphical control element that presents a Tabular View of data. A typical Grid View also supports some or all of the following: Clicking a column header to change the sort order of the grid. Dragging column headers to change their size and their order.

The GridView control displays the values of a data source in a table. Each column represents a field, while each row represents a record.

Description
This article shows you how to export GridView records in Excel and PDF. Before that, read my previus article carefully.

http://www.c-sharpcorner.com/article/crud-using-stored-procedure-in-asp-net-gridview-real-time/


Only a small modification is added in this article for exporting image buttons. So, there is no need to describe same things as I described in my previous article.

Steps to be Followed
Step1

I have created one ASP.NET web application named "GridViewDemo". Then, add an ASP.NET web page named "GridViewDemo.aspx". Then add images in Images folder (check attached file).

Code ref for GridViewDemo.aspx,
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo.aspx.cs" Inherits="GridViewDemo.GridViewDemo" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title>Satyaprakash Samantaray</title>
  6. <%--Botstrap Part--%>
  7. <style>
  8. .button {
  9. background-color: #4CAF50;
  10. border: none;
  11. color: white;
  12. padding: 15px 32px;
  13. text-align: center;
  14. text-decoration: none;
  15. display: inline-block;
  16. font-size: 16px;
  17. margin: 4px 2px;
  18. cursor: pointer;
  19. }
  20. .DataGridFixedHeader {
  21. color: White;
  22. font-size: 13px;
  23. font-family: Verdana;
  24. background-color:yellow
  25. }
  26. .grid_item {
  27. background-color: #E3EAEB;
  28. border-width: 1px;
  29. font-family: Verdana;
  30. border-style: solid;
  31. font-size: 12pt;
  32. color: black;
  33. border: 1px solid black;
  34. }
  35. .grid_alternate {
  36. border-width: 1px;
  37. font-family: Verdana;
  38. border-style: solid;
  39. font-size: 12pt;
  40. color: black;
  41. background-color: White;
  42. }
  43. .button4 {
  44. border-radius: 9px;
  45. }
  46. input[type=text], select {
  47. width: 40%;
  48. padding: 12px 20px;
  49. margin: 10px 0;
  50. display: inline-block;
  51. border: 1px solid #ccc;
  52. border-radius: 4px;
  53. box-sizing: border-box;
  54. font-family: 'Montserrat', sans-serif;
  55. text-indent: 10px;
  56. color: blue;
  57. text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  58. font-size: 20px;
  59. }
  60. </style>
  61. <%--Botstrap Part--%>
  62. </head>
  63. <body>
  64. <form id="form1" runat="server">
  65. <fieldset>
  66. <legend style="font-family: Arial Black;background-color:yellow; color:red; font-size:larger;font-style: oblique">Satyaprakash's Real-Time Project</legend>
  67. <table align="center">
  68. <tr>
  69. <td colspan="2" align="center" class="auto-style1">
  70. <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">Satyaprakash's Real-Time GridView Export Excel and Pdf In Asp.Net</h2>
  71. </td>
  72. </tr>
  73. <tr>
  74. <td style="text-align:center">
  75. <asp:TextBox runat="server" ID="txtFirstName" placeholder="Enter First Name.." ValidationGroup="add" ></asp:TextBox>
  76. </td>
  77. </tr>
  78. <tr>
  79. <td style="text-align:center">
  80. <asp:TextBox runat="server" ID="txtLastName" placeholder="Enter Last Name.." ValidationGroup="add" ></asp:TextBox>
  81. </td>
  82. </tr>
  83. <tr>
  84. <td style="text-align:center">
  85. <asp:TextBox runat="server" placeholder="Enter Phone Number.." ID="txtPhoneNumber" ValidationGroup="add"></asp:TextBox>
  86. </td>
  87. <td></td>
  88. </tr>
  89. <tr>
  90. <td style="text-align:center">
  91. <asp:TextBox runat="server" ID="txtEmailAddress" placeholder="Enter Email Address.." ValidationGroup="add" ></asp:TextBox>
  92. </td>
  93. </tr>
  94. <tr>
  95. <td style="text-align:center">
  96. <asp:TextBox runat="server" ID="txtSalary" placeholder="Enter Salary.." ValidationGroup="add" ></asp:TextBox>
  97. </td>
  98. </tr>
  99. <tr>
  100. <td colspan="2" align="center">
  101. <asp:Button runat="server" ID="btnAddEmployee" Text="Add" OnClick="btnAddEmployee_Click" class="button button4" ValidationGroup="add"/>
  102. <asp:Button runat="server" ID="btnUpdate" Text="Update" class="button button4" OnClick="btnUpdate_Click"/>
  103. <asp:Button runat="server" ID="btnReset" Text="Reset" class="button button4" OnClick="btnReset_Click"/>
  104. </td>
  105. </tr>
  106. <tr>
  107. <td colspan="2" align="center">
  108. <br />
  109. <asp:Label runat="server" ID="lblMessage"></asp:Label>
  110. <br />
  111. <br />
  112. </td>
  113. </tr>
  114. <tr runat="server" style="height: 3px">
  115. <td align="center" colspan="2" style="background-color:yellowgreen;width: 100%;">
  116. <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export EXCEL</span>
  117. <asp:ImageButton ID="ibtnExcel" runat="server" AlternateText="Click here to Export to Excel" BorderColor="black" ImageAlign="Middle" ImageUrl="~/Images/Excel.gif" Style="height: 30px" ToolTip="Click here to Export to Excel" OnClick="ibtnExcel_Click"/>
  118. <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export PDF</span>
  119. <asp:ImageButton ID="ibtnPdf" runat="server" AlternateText="Click here to Export to Pdf" BorderColor="black" ImageAlign="Middle" ImageUrl="~/Images/Pdf.png" Style="height: 20px" ToolTip="Click here to Export to Pdf" OnClick="ibtnPdf_Click" />
  120. </td>
  121. </tr>
  122. <tr>
  123. <td colspan="2">
  124. <asp:GridView ID="grvEmployee" runat="server" AllowPaging="true" CellPadding="2" EnableModelValidation="True"
  125. ForeColor="red" GridLines="Both" ItemStyle-HorizontalAlign="center" EmptyDataText="There Is No Records In Database!" AutoGenerateColumns="false" Width="1100px"
  126. HeaderStyle-ForeColor="blue" OnPageIndexChanging="grvEmployee_PageIndexChanging" OnRowCancelingEdit="grvEmployee_RowCancelingEdit" OnRowDeleting="grvEmployee_RowDeleting" OnRowEditing="grvEmployee_RowEditing">
  127. <HeaderStyle CssClass="DataGridFixedHeader" />
  128. <RowStyle CssClass="grid_item" />
  129. <AlternatingRowStyle CssClass="grid_alternate" />
  130. <FooterStyle CssClass="DataGridFixedHeader" />
  131. <Columns>
  132. <asp:TemplateField HeaderText="EmpId">
  133. <HeaderStyle HorizontalAlign="Left" />
  134. <ItemStyle HorizontalAlign="Left" />
  135. <ItemTemplate>
  136. <asp:Label runat="server" ID="lblEmpId" Text='<%#Eval("id") %>'></asp:Label>
  137. </ItemTemplate>
  138. </asp:TemplateField>
  139. <asp:TemplateField HeaderText="FirstName">
  140. <HeaderStyle HorizontalAlign="Left" />
  141. <ItemStyle HorizontalAlign="Left" />
  142. <ItemTemplate>
  143. <asp:Label runat="server" ID="lblFirstName" Text='<%#Eval("FirstName") %>'></asp:Label>
  144. </ItemTemplate>
  145. </asp:TemplateField>
  146. <asp:TemplateField HeaderText="LastName">
  147. <HeaderStyle HorizontalAlign="Left" />
  148. <ItemStyle HorizontalAlign="Left" />
  149. <ItemTemplate>
  150. <asp:Label runat="server" ID="lblLastName" Text='<%#Eval("LastName") %>'></asp:Label>
  151. </ItemTemplate>
  152. </asp:TemplateField>
  153. <asp:TemplateField HeaderText="Phone No.">
  154. <HeaderStyle HorizontalAlign="Left" />
  155. <ItemStyle HorizontalAlign="Left" />
  156. <ItemTemplate>
  157. <asp:Label runat="server" ID="lblPhoneNumber" Text='<%#Eval("PhoneNumber") %>'></asp:Label>
  158. </ItemTemplate>
  159. </asp:TemplateField>
  160. <asp:TemplateField HeaderText="Email">
  161. <HeaderStyle HorizontalAlign="Left" />
  162. <ItemStyle HorizontalAlign="Left" />
  163. <ItemTemplate>
  164. <asp:Label runat="server" ID="lblEmailAddress" Text='<%#Eval("EmailAddress") %>'></asp:Label>
  165. </ItemTemplate>
  166. </asp:TemplateField>
  167. <asp:TemplateField HeaderText="Salary">
  168. <HeaderStyle HorizontalAlign="Left" />
  169. <ItemStyle HorizontalAlign="Left" />
  170. <ItemTemplate>
  171. <asp:Label runat="server" ID="lblSalary" Text='<%#Eval("Salary") %>'></asp:Label>
  172. </ItemTemplate>
  173. </asp:TemplateField>
  174. <asp:TemplateField HeaderText="Update">
  175. <HeaderStyle HorizontalAlign="Left" />
  176. <ItemStyle HorizontalAlign="Left" />
  177. <ItemTemplate>
  178. <asp:LinkButton runat="server" ID="btnEdit" Text="Edit" CommandName="Edit" ToolTip="Click here to Edit the record" />
  179. </ItemTemplate>
  180. </asp:TemplateField>
  181. <asp:TemplateField HeaderText="Delete">
  182. <HeaderStyle HorizontalAlign="Left" />
  183. <ItemStyle HorizontalAlign="Left" />
  184. <ItemTemplate>
  185. <asp:LinkButton runat="server" ID="btnDelete" Text="Delete" CommandName="Delete" OnClientClick="return confirm('Are You Sure You want to Delete the Record?');" ToolTip="Click here to Delete the record" />
  186. </span>
  187. </ItemTemplate>
  188. </asp:TemplateField>
  189. </Columns>
  190. </asp:GridView>
  191. </td>
  192. </tr>
  193. </table>
  194. </fieldset>
  195. </form>
  196. </body>
  197. <br />
  198. <br />
  199. <footer>
  200. <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© <script> document.write(new Date().toDateString()); </script></p>
  201. </footer>
  202. </html>
Code Description

Here, I have added two image buttons to perform export to Excel and PDF.
  1. <tr runat="server" style="height: 3px">
  2. <td align="center" colspan="2" style="background-color:yellowgreen;width: 100%;">
  3. <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export EXCEL</span>
  4. <asp:ImageButton ID="ibtnExcel" runat="server" AlternateText="Click here to Export to Excel" BorderColor="black" ImageAlign="Middle" ImageUrl="~/Images/Excel.gif" Style="height: 30px" ToolTip="Click here to Export to Excel" OnClick="ibtnExcel_Click"/>
  5. <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export PDF</span>
  6. <asp:ImageButton ID="ibtnPdf" runat="server" AlternateText="Click here to Export to Pdf" BorderColor="black" ImageAlign="Middle" ImageUrl="~/Images/Pdf.png" Style="height: 20px" ToolTip="Click here to Export to Pdf" OnClick="ibtnPdf_Click" />
  7. </td>
  8. </tr>
I have mentioned image path as -
  1. ImageUrl="~/Images/Excel.gif"
  2. ImageUrl="~/Images/Pdf.png"
I have added tooltip for both image buttons -
  1. ToolTip="Click here to Export to Excel"
  2. ToolTip="Click here to Export to Pdf"
Step2

Code ref for GridViewDemo.aspx.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Web;
  10. using System.Web.UI;
  11. using System.Web.UI.WebControls;
  12. //namespace for pdf export.
  13. using System.Text;
  14. using iTextSharp.text.pdf;
  15. using iTextSharp.text.html;
  16. using iTextSharp.text.html.simpleparser;
  17. using System.Web.UI.HtmlControls;
  18. namespace GridViewDemo
  19. {
  20. public partial class GridViewDemo : System.Web.UI.Page
  21. {
  22. private string strConnectionString = ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
  23. private SqlCommand _sqlCommand;
  24. private SqlDataAdapter _sqlDataAdapter;
  25. DataSet _dtSet;
  26. protected void Page_Load(object sender, EventArgs e)
  27. {
  28. if (!IsPostBack)
  29. {
  30. BindEmployeeData();
  31. }
  32. btnUpdate.Visible = false;
  33. btnAddEmployee.Visible = true;
  34. }
  35. private static void ShowAlertMessage(string error)
  36. {
  37. System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
  38. if (page != null)
  39. {
  40. error = error.Replace("'", "\'");
  41. System.Web.UI.ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + error + "');", true);
  42. }
  43. }
  44. public void CreateConnection()
  45. {
  46. SqlConnection _sqlConnection = new SqlConnection(strConnectionString);
  47. _sqlCommand = new SqlCommand();
  48. _sqlCommand.Connection = _sqlConnection;
  49. }
  50. public void OpenConnection()
  51. {
  52. _sqlCommand.Connection.Open();
  53. }
  54. public void CloseConnection()
  55. {
  56. _sqlCommand.Connection.Close();
  57. }
  58. public void DisposeConnection()
  59. {
  60. _sqlCommand.Connection.Dispose();
  61. }
  62. public void BindEmployeeData()
  63. {
  64. try
  65. {
  66. CreateConnection();
  67. OpenConnection();
  68. _sqlCommand.CommandText = "Sp_GridCrud";
  69. _sqlCommand.CommandType = CommandType.StoredProcedure;
  70. _sqlCommand.Parameters.AddWithValue("@Event", "Select");
  71. _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
  72. _dtSet = new DataSet();
  73. _sqlDataAdapter.Fill(_dtSet);
  74. grvEmployee.DataSource = _dtSet;
  75. grvEmployee.DataBind();
  76. }
  77. catch (Exception ex)
  78. {
  79. Response.Redirect("The Error is " + ex);
  80. }
  81. finally
  82. {
  83. CloseConnection();
  84. DisposeConnection();
  85. }
  86. }
  87. protected void btnAddEmployee_Click(object sender, EventArgs e)
  88. {
  89. try
  90. {
  91. CreateConnection();
  92. OpenConnection();
  93. _sqlCommand.CommandText = "Sp_GridCrud";
  94. _sqlCommand.CommandType = CommandType.StoredProcedure;
  95. _sqlCommand.Parameters.AddWithValue("@Event", "Add");
  96. _sqlCommand.Parameters.AddWithValue("@FirstName", Convert.ToString(txtFirstName.Text.Trim()));
  97. _sqlCommand.Parameters.AddWithValue("@LastName", Convert.ToString(txtLastName.Text.Trim()));
  98. _sqlCommand.Parameters.AddWithValue("@PhoneNumber", Convert.ToString(txtPhoneNumber.Text.Trim()));
  99. _sqlCommand.Parameters.AddWithValue("@EmailAddress", Convert.ToString(txtEmailAddress.Text.Trim()));
  100. _sqlCommand.Parameters.AddWithValue("@Salary", Convert.ToDecimal(txtSalary.Text));
  101. int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());
  102. if (result > 0)
  103. {
  104. ShowAlertMessage("Record Is Inserted Successfully");
  105. BindEmployeeData();
  106. ClearControls();
  107. }
  108. else
  109. {
  110. ShowAlertMessage("Failed");
  111. }
  112. }
  113. catch (Exception ex)
  114. {
  115. ShowAlertMessage("Check your input data");
  116. }
  117. finally
  118. {
  119. CloseConnection();
  120. DisposeConnection();
  121. }
  122. }
  123. public void ClearControls()
  124. {
  125. txtFirstName.Text = "";
  126. txtLastName.Text = "";
  127. txtPhoneNumber.Text = "";
  128. txtEmailAddress.Text = "";
  129. txtSalary.Text = "";
  130. }
  131. protected void grvEmployee_RowEditing(object sender, GridViewEditEventArgs e)
  132. {
  133. btnAddEmployee.Visible = false;
  134. btnUpdate.Visible = true;
  135. int RowIndex = e.NewEditIndex;
  136. Label empid = (Label)grvEmployee.Rows[RowIndex].FindControl("lblEmpId");
  137. Session["id"] = empid.Text;
  138. txtFirstName.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblFirstName")).Text.ToString();
  139. txtLastName.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblLastName")).Text.ToString();
  140. txtPhoneNumber.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblPhoneNumber")).Text.ToString();
  141. txtEmailAddress.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblEmailAddress")).Text.ToString();
  142. txtSalary.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblSalary")).Text.ToString();
  143. }
  144. protected void grvEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)
  145. {
  146. try
  147. {
  148. CreateConnection();
  149. OpenConnection();
  150. Label id = (Label)grvEmployee.Rows[e.RowIndex].FindControl("lblEmpId");
  151. _sqlCommand.CommandText = "Sp_GridCrud";
  152. _sqlCommand.Parameters.AddWithValue("@Event", "Delete");
  153. _sqlCommand.Parameters.AddWithValue("@EmpId", Convert.ToInt32(id.Text));
  154. _sqlCommand.CommandType = CommandType.StoredProcedure;
  155. int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());
  156. if (result > 0)
  157. {
  158. ShowAlertMessage("Record Is Deleted Successfully");
  159. grvEmployee.EditIndex = -1;
  160. BindEmployeeData();
  161. }
  162. else
  163. {
  164. lblMessage.Text = "Failed";
  165. lblMessage.ForeColor = System.Drawing.Color.Red;
  166. BindEmployeeData();
  167. }
  168. }
  169. catch (Exception ex)
  170. {
  171. ShowAlertMessage("Check your input data");
  172. }
  173. finally
  174. {
  175. CloseConnection();
  176. DisposeConnection();
  177. }
  178. }
  179. protected void grvEmployee_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
  180. {
  181. grvEmployee.EditIndex = -1;
  182. BindEmployeeData();
  183. }
  184. protected void grvEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
  185. {
  186. grvEmployee.PageIndex = e.NewPageIndex;
  187. BindEmployeeData();
  188. }
  189. protected void btnReset_Click(object sender, EventArgs e)
  190. {
  191. ClearControls();
  192. }
  193. protected void btnUpdate_Click(object sender, EventArgs e)
  194. {
  195. try
  196. {
  197. CreateConnection();
  198. OpenConnection();
  199. _sqlCommand.CommandText = "Sp_GridCrud";
  200. _sqlCommand.CommandType = CommandType.StoredProcedure;
  201. _sqlCommand.Parameters.AddWithValue("@Event", "Update");
  202. _sqlCommand.Parameters.AddWithValue("@FirstName", Convert.ToString(txtFirstName.Text.Trim()));
  203. _sqlCommand.Parameters.AddWithValue("@LastName", Convert.ToString(txtLastName.Text.Trim()));
  204. _sqlCommand.Parameters.AddWithValue("@PhoneNumber", Convert.ToString(txtPhoneNumber.Text.Trim()));
  205. _sqlCommand.Parameters.AddWithValue("@EmailAddress", Convert.ToString(txtEmailAddress.Text.Trim()));
  206. _sqlCommand.Parameters.AddWithValue("@Salary", Convert.ToDecimal(txtSalary.Text));
  207. _sqlCommand.Parameters.AddWithValue("@EmpId", Convert.ToDecimal(Session["id"]));
  208. int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());
  209. if (result > 0)
  210. {
  211. ShowAlertMessage("Record Is Updated Successfully");
  212. grvEmployee.EditIndex = -1;
  213. BindEmployeeData();
  214. ClearControls();
  215. }
  216. else
  217. {
  218. ShowAlertMessage("Failed");
  219. }
  220. }
  221. catch (Exception ex)
  222. {
  223. ShowAlertMessage("Check your input data");
  224. }
  225. finally
  226. {
  227. CloseConnection();
  228. DisposeConnection();
  229. }
  230. }
  231. protected void ibtnExcel_Click(object sender, ImageClickEventArgs e)
  232. {
  233. try
  234. {
  235. GridView grvEmployee = new GridView();
  236. CreateConnection();
  237. OpenConnection();
  238. _sqlCommand.CommandText = "Sp_GridCrud";
  239. _sqlCommand.CommandType = CommandType.StoredProcedure;
  240. _sqlCommand.Parameters.AddWithValue("@Event", "Select");
  241. _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
  242. _dtSet = new DataSet();
  243. _sqlDataAdapter.Fill(_dtSet);
  244. grvEmployee.DataSource = _dtSet;
  245. grvEmployee.DataBind();
  246. HttpContext.Current.Response.ClearContent();
  247. HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=SatyaRecords.xls");
  248. HttpContext.Current.Response.ContentType = "application/excel";
  249. StringWriter sw = new StringWriter();
  250. HtmlTextWriter htw = new HtmlTextWriter(sw);
  251. grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
  252. grvEmployee.HeaderStyle.ForeColor = Color.White;
  253. grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
  254. grvEmployee.RenderControl(htw);
  255. HttpContext.Current.Response.Write(sw.ToString());
  256. HttpContext.Current.Response.Flush();
  257. HttpContext.Current.Response.End();
  258. }
  259. catch (Exception ex)
  260. {
  261. HttpContext.Current.Response.Flush();
  262. HttpContext.Current.Response.End();
  263. }
  264. }
  265. protected void ibtnPdf_Click(object sender, ImageClickEventArgs e)
  266. {
  267. try
  268. {
  269. GridView grvEmployee = new GridView();
  270. CreateConnection();
  271. OpenConnection();
  272. _sqlCommand.CommandText = "Sp_GridCrud";
  273. _sqlCommand.CommandType = CommandType.StoredProcedure;
  274. _sqlCommand.Parameters.AddWithValue("@Event", "Select");
  275. _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
  276. _dtSet = new DataSet();
  277. _sqlDataAdapter.Fill(_dtSet);
  278. grvEmployee.DataSource = _dtSet;
  279. grvEmployee.DataBind();
  280. Response.ContentType = "application/pdf";
  281. Response.AddHeader("content-disposition", "attachment;filename=SatyaRecords.pdf");
  282. Response.Cache.SetCacheability(HttpCacheability.NoCache);
  283. StringWriter swr = new StringWriter();
  284. HtmlTextWriter htmlwr = new HtmlTextWriter(swr);
  285. //Mention gridview property for export to pdf.
  286. grvEmployee.AllowPaging = false;
  287. grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
  288. grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
  289. grvEmployee.HeaderRow.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
  290. grvEmployee.HeaderRow.Style.Add("font-size", "8.20px");
  291. grvEmployee.HeaderRow.Style.Add("color", "White");
  292. grvEmployee.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
  293. grvEmployee.Style.Add("font-size", "8px");
  294. for (int i = 0; i < grvEmployee.Rows.Count; i++)
  295. {
  296. grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;
  297. //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;
  298. }
  299. grvEmployee.RenderControl(htmlwr);
  300. StringReader srr = new StringReader(swr.ToString());
  301. //iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 10f); //Pdf Page size and Margin types. //For Portrait
  302. iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10f, 10f, 10f, 10f); //For Landscape
  303. HTMLWorker htmlparser = new HTMLWorker(pdfdoc);
  304. PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
  305. pdfdoc.Open();
  306. htmlparser.Parse(srr);
  307. pdfdoc.Close();
  308. Response.Write(pdfdoc);
  309. Response.End();
  310. }
  311. catch (Exception ex)
  312. {
  313. }
  314. }
  315. }
  316. }
Code Description

I have added some namespaces for PDF export.
  1. using System.Text;
  2. using iTextSharp.text.pdf;
  3. using iTextSharp.text.html;
  4. using iTextSharp.text.html.simpleparser;
  5. using System.Web.UI.HtmlControls;
For that, I have added one DLL file named "itextsharp.dll" . A free PDF library is ported from Java iText.
Then, in button click event of Excel export, I have added the following code.
  1. protected void ibtnExcel_Click(object sender, ImageClickEventArgs e)
  2. {
  3. try
  4. {
  5. GridView grvEmployee = new GridView();
  6. CreateConnection();
  7. OpenConnection();
  8. _sqlCommand.CommandText = "Sp_GridCrud";
  9. _sqlCommand.CommandType = CommandType.StoredProcedure;
  10. _sqlCommand.Parameters.AddWithValue("@Event", "Select");
  11. _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
  12. _dtSet = new DataSet();
  13. _sqlDataAdapter.Fill(_dtSet);
  14. grvEmployee.DataSource = _dtSet;
  15. grvEmployee.DataBind();
  16. HttpContext.Current.Response.ClearContent();
  17. HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=SatyaRecords.xls");
  18. HttpContext.Current.Response.ContentType = "application/excel";
  19. StringWriter sw = new StringWriter();
  20. HtmlTextWriter htw = new HtmlTextWriter(sw);
  21. grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
  22. grvEmployee.HeaderStyle.ForeColor = Color.White;
  23. grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
  24. grvEmployee.RenderControl(htw);
  25. HttpContext.Current.Response.Write(sw.ToString());
  26. HttpContext.Current.Response.Flush();
  27. HttpContext.Current.Response.End();
  28. }
  29. catch (Exception ex)
  30. {
  31. HttpContext.Current.Response.Flush();
  32. HttpContext.Current.Response.End();
  33. }
  34. }
Here, I have created a dynamic object for GridView and put stored procedure and appropriate ADO.NET related objects to fetch data.
  1. GridView grvEmployee = new GridView();
  2. CreateConnection();
  3. OpenConnection();
  4. _sqlCommand.CommandText = "Sp_GridCrud";
  5. _sqlCommand.CommandType = CommandType.StoredProcedure;
  6. _sqlCommand.Parameters.AddWithValue("@Event", "Select");
  7. _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
  8. _dtSet = new DataSet();
  9. _sqlDataAdapter.Fill(_dtSet);
  10. grvEmployee.DataSource = _dtSet;
  11. grvEmployee.DataBind();
Then, I have added some style to GridView.
  1. grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
  2. grvEmployee.HeaderStyle.ForeColor = Color.White;
  3. grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
  4. grvEmployee.RenderControl(htw);
Then, I added code for export to Excel with specified Excel sheet name.
  1. HttpContext.Current.Response.ClearContent();
  2. HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=SatyaRecords.xls");
  3. HttpContext.Current.Response.ContentType = "application/excel";
  4. StringWriter sw = new StringWriter();
  5. HtmlTextWriter htw = new HtmlTextWriter(sw);
  6. HttpContext.Current.Response.Write(sw.ToString());
  7. HttpContext.Current.Response.Flush();
  8. HttpContext.Current.Response.End();
Note - Response.Flush forces all currently buffered output to be sent to the client. The Flush method can be called multiple times during the request processing.

Response.End sends all the currently buffered output to the client, stops execution of the page, and raises the EndRequest event.

You should try using this code if you are not doing any processing on the page after Response.Write and want to stop processing the page.
  1. context.HttpContext.Response.Clear();
  2. context.HttpContext.Response.Write(htmlString);
  3. context.HttpContext.Response.Flush(); // send all buffered output to client
  4. context.HttpContext.Response.End(); // response.end would work fine now.
In the PDF button click event, I have added code for Export data to PDF format.
  1. protected void ibtnPdf_Click(object sender, ImageClickEventArgs e)
  2. {
  3. try
  4. {
  5. GridView grvEmployee = new GridView();
  6. CreateConnection();
  7. OpenConnection();
  8. _sqlCommand.CommandText = "Sp_GridCrud";
  9. _sqlCommand.CommandType = CommandType.StoredProcedure;
  10. _sqlCommand.Parameters.AddWithValue("@Event", "Select");
  11. _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
  12. _dtSet = new DataSet();
  13. _sqlDataAdapter.Fill(_dtSet);
  14. grvEmployee.DataSource = _dtSet;
  15. grvEmployee.DataBind();
  16. Response.ContentType = "application/pdf";
  17. Response.AddHeader("content-disposition", "attachment;filename=SatyaRecords.pdf");
  18. Response.Cache.SetCacheability(HttpCacheability.NoCache);
  19. StringWriter swr = new StringWriter();
  20. HtmlTextWriter htmlwr = new HtmlTextWriter(swr);
  21. //Mention gridview property for export to pdf.
  22. grvEmployee.AllowPaging = false;
  23. grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
  24. grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
  25. grvEmployee.HeaderRow.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
  26. grvEmployee.HeaderRow.Style.Add("font-size", "8.20px");
  27. grvEmployee.HeaderRow.Style.Add("color", "White");
  28. grvEmployee.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
  29. grvEmployee.Style.Add("font-size", "8px");
  30. for (int i = 0; i < grvEmployee.Rows.Count; i++)
  31. {
  32. grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;
  33. //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;
  34. }
  35. grvEmployee.RenderControl(htmlwr);
  36. StringReader srr = new StringReader(swr.ToString());
  37. //iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 10f); //Pdf Page size and Margin types. //For Portrait
  38. iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10f, 10f, 10f, 10f); //For Landscape
  39. HTMLWorker htmlparser = new HTMLWorker(pdfdoc);
  40. PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
  41. pdfdoc.Open();
  42. htmlparser.Parse(srr);
  43. pdfdoc.Close();
  44. Response.Write(pdfdoc);
  45. Response.End();
  46. }
  47. catch (Exception ex)
  48. {
  49. }
  50. }
Here, I have created a dynamic object for GridView and put stored procedure and appropriate ADO.NET related objects to fetch data.
  1. GridView grvEmployee = new GridView();
  2. CreateConnection();
  3. OpenConnection();
  4. _sqlCommand.CommandText = "Sp_GridCrud";
  5. _sqlCommand.CommandType = CommandType.StoredProcedure;
  6. _sqlCommand.Parameters.AddWithValue("@Event", "Select");
  7. _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
  8. _dtSet = new DataSet();
  9. _sqlDataAdapter.Fill(_dtSet);
  10. grvEmployee.DataSource = _dtSet;
  11. grvEmployee.DataBind();
Then, I added some style to GridView.
  1. grvEmployee.AllowPaging = false;
  2. grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
  3. grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
  4. grvEmployee.HeaderRow.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
  5. grvEmployee.HeaderRow.Style.Add("font-size", "8.20px");
  6. grvEmployee.HeaderRow.Style.Add("color", "White");
  7. grvEmployee.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
  8. grvEmployee.Style.Add("font-size", "8px");
  9. for (int i = 0; i < grvEmployee.Rows.Count; i++)
  10. {
  11. grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;
  12. //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;
  13. }
Then, I added code for Export to PDF with specified PDF name.
  1. Response.ContentType = "application/pdf";
  2. Response.AddHeader("content-disposition", "attachment;filename=SatyaRecords.pdf");
  3. Response.Cache.SetCacheability(HttpCacheability.NoCache);
  4. StringWriter swr = new StringWriter();
  5. HtmlTextWriter htmlwr = new HtmlTextWriter(swr);
  6. for (int i = 0; i < grvEmployee.Rows.Count; i++)
  7. {
  8. grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;
  9. //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;
  10. }
  11. grvEmployee.RenderControl(htmlwr);
  12. StringReader srr = new StringReader(swr.ToString());
  13. //iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 10f); //Pdf Page size and Margin types. //For Portrait
  14. iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10f, 10f, 10f, 10f); //For Landscape
  15. HTMLWorker htmlparser = new HTMLWorker(pdfdoc);
  16. PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
  17. pdfdoc.Open();
  18. htmlparser.Parse(srr);
  19. pdfdoc.Close();
  20. Response.Write(pdfdoc);
  21. Response.End();
OUTPUT

I have added only this part to the existing one as mentioned in my previous article.

Then, Export to Excel.
Compare Excel sheet data with GridView.

Then, export to PDF.

Compare PDF data with GridView.


GIF images for better understanding


Summary
  1. What is GridView in ASP.NET.
  2. Single stored procedure to Export PDF and Excel.
  3. Image buttons added.
  4. Styles to be added in Excel and PDF after GridView Export.