26 September, 2012

Export to .xls,.pdf,.doc and formatted .pdf from gridview using C# in ASP.NET

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

    protected void ASPNET_MSgBox(string L_Message)
    {
        string L_Script = "";
        L_Script = "<script> alert('" + L_Message + "');</script>";
        Page.RegisterClientScriptBlock("Information!!", L_Script);
    }
    private void loadData()
    {
        try
        {
            string query = "";
            using (SqlConnection _SqlConnection = new SqlConnection(Global.connString))
            {
                _SqlConnection.Open();
                SqlCommand _SqlCommand = _SqlConnection.CreateCommand();
                query = @"Exec Procedure 2";
                SqlDataAdapter _SqlDataAdapter = new SqlDataAdapter(query, _SqlConnection);
                DataSet ds = new DataSet();
                _SqlDataAdapter.Fill(ds, "dt");
                DataTable dt = ds.Tables["dt"];
                gvPVPFinal.DataSource = dt;               
                gvPVPFinal.DataBind();
            }
        }
        catch
        {
            ASPNET_MSgBox("ERROR: Approved Priority Visit Planning (PVP).\\nContact with Administrator");
        }
    }
    private void ExportGridViewToExcel()
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=Export.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        /*--------------Change GridView control under a Form------------------*/
        HtmlForm frm = new HtmlForm();
        GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);
        frm.RenderControl(htmlWrite);
        /*--------------------------------*/
        //gvRegion.RenderControl(htmlWrite);
        Response.Write(stringWrite);
        Response.End();
    }
    private void ExportGridViewToFormatedPDF()
    {
        DataTable dt;
        try
        {
            string query = "";
            using (SqlConnection _SqlConnection = new SqlConnection(Global.connString))
            {
                _SqlConnection.Open();
                SqlCommand _SqlCommand = _SqlConnection.CreateCommand();
                query = @"Exec spPVPfinal '" + cmbTerritory.Text.ToString() + "',2";
                SqlDataAdapter _SqlDataAdapter = new SqlDataAdapter(query, _SqlConnection);
                DataSet ds = new DataSet();
                _SqlDataAdapter.Fill(ds, "PVPFianl");
                dt = ds.Tables["PVPFianl"];

                //Create a table
                iTextSharp.text.Table table = new iTextSharp.text.Table(GridView1.Columns.Count);
                table.Cellpadding = 5;
                //Set the column widths
                int[] widths = { 100, 250, 90, 50, 50, 380, 380 };

                for (int x = 0; x < GridView1.Columns.Count; x++)
                {
                    string cellText = Server.HtmlDecode(GridView1.HeaderRow.Cells[x].Text);
                    iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);
                    cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#C2D69B"));
                    table.AddCell(cell);
                }
                table.SetWidths(widths);
                //Transfer rows from GridView to table
                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
                    {
                        for (int j = 0; j < GridView1.Columns.Count; j++)
                        {
                            string cellText = Server.HtmlDecode(dt.Rows[i][j].ToString());
                            iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);
                            //Set Color of Alternating row
                            //if (i % 2 != 0)
                            //{
                            //    cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#C2D69B"));
                            //}                
                            table.AddCell(cell);
                        }
                    }
                }
                //Create the PDF Document
                Document pdfDoc = new Document(PageSize.A4.Rotate(), 5f, 5f, 5f, 5f);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                pdfDoc.Add(table);
                pdfDoc.Close();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Write(pdfDoc);
                Response.End();
            }
        }
        catch
        {
            //ASPNET_MSgBox("ERROR: Download Priority Visit Planning (PVP).\\nContact with Administrator");
        }
    }
    private void ExportGridViewToPDF()
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);
        frm.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4.Rotate(), 5f, 5f, 5f, 5f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
    private void ExportGridViewToWord()
    {
        Response.AddHeader("content-disposition", "attachment;filename=Export.doc");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.word";

        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        HtmlForm frm = new HtmlForm();
        GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);
        frm.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());
        Response.End();
    }

 N.B.:
 add reference this dll : itextsharp.dll 
 please download .DLL from here : itextsharp.dll