Saturday, August 8, 2015

How to Export GridView data To Word, Excel, PDF, Formats in ASP.Net

Step 1.
First create a new table named tbl_ClientInformation for showing data in gridview and which we have to convert in Word, Excel and PDF formats.

             

And now insert some dummy data in this table.

Step 2.

After creating a new project first we have to make changes in HTML file and put some buttons for converting shown gridview data in different different formats as shown below.

          

Following is HTML code for this design.
<form id="form1" runat="server">
<asp:GridView ID="gv" runat="server"
AutoGenerateColumns="false" Font-Names="Arial"
Font-Size="11pt" AlternatingRowStyle-BackColor="#C2D69B"
HeaderStyle-BackColor="green" AllowPaging="true">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="ClientID"
HeaderText="Client ID" />
<asp:BoundField ItemStyle-Width="150px" DataField="ClientName"
HeaderText="Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="Address"
HeaderText="Address" />
</Columns>
</asp:GridView>
<asp:Button ID="ButtonWord" runat="server" OnClick="ButtonWord_Click" Text="To Word" />
<asp:Button ID="ButtonExcel" runat="server" OnClick="ButtonExcel_Click" Text="To Excel" />
<asp:Button ID="ButtonPDF" runat="server" OnClick="ButtonPDF_Click" Text="To PDF" />
</form>
Step 3.

In code behind first we have to add a new package to reference assembly named itextsharp.

for installing it go to references right click on it and click on Manage Nu get packages and search for itextsharp and install it.

Step 4.

After installing it check for these namespaces are present in code or not. If not then add them in code.

      using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Web;

Step 5.
For showing gridview data first we have to add these piece of code.

String str = "Data Source=JITENDRA-PC\\SQLEXPRESS; Initial Catalog= Vaibhav_Task; Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{

BindData();

}

}

private void BindData()
{

DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(str))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from tbl_ClientInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
gv.DataSource = ds;
gv.DataBind();
}
}




Step 6.

For avoiding exception add this method after Step 5.

public override void VerifyRenderingInServerForm(Control control)
{

}

Step 7.

We have created buttons for converting grid view data to Word, Excel and PDF formats so on button click events of following buttons add this piece of code.

1.   //For converting in Excel format
protected void ButtonExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;

Response.AddHeader("content-disposition",
"attachment;filename=GVExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
//Change the Header Row back to white color
gv.HeaderRow.Style.Add("background-color", "#FFFFFF");

//Apply style to Individual Cells
gv.HeaderRow.Cells[0].Style.Add("background-color", "green");
gv.HeaderRow.Cells[1].Style.Add("background-color", "green");
gv.HeaderRow.Cells[2].Style.Add("background-color", "green");

for (int i = 0; i < gv.Rows.Count; i++)
{
GridViewRow row = gv.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");
}
}
gv.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();
gv.AllowPaging = false;
gv.DataBind();
}

2. //For converting in Word format
protected void ButtonWord_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GVExport.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();                                                            
HtmlTextWriter hw = new HtmlTextWriter(sw);
      gv.RenderControl(hw);
      Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
gv.AllowPaging = false;
gv.DataBind();
}


3. //For converting in PDF format

protected void ButtonPDF_Click(object sender, EventArgs e)
{

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GVExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.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();
gv.AllowPaging = true;
gv.DataBind();
}


OUTPUT -
On Clicking the buttons you will asked for saving documents click OK and get the expected output.


No comments:

Post a Comment

Rewrite whole Web Site System and Sub System with data migration to new system.

Can you please share me your skype id or whats up number for better communications  my skype id is - jitendra.tech  whats up - +919617741414...