Tuesday 22 May 2012

Export gridview data to Excel/Word/PDF document in asp.net





https://impactmarketingservice.co.in/ciscobangaloreevent/Registraiondetails.aspx





using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Net;

public partial class Registraiondetails : System.Web.UI.Page
{
    public SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["Con"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindgrid();
        }
    }
    public void bindgrid()
    {
        string sql = "select * from msppt_com_impact.ASAXPartnerEDM_Reg order by id asc";
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        bindgrid();
        //Change the Header Row back to white color
        GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
        //Applying stlye to gridview header cells
        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
        {
            GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
        }
        int j = 1;
        //This loop is used to apply stlye to cells based on particular row
        foreach (GridViewRow gvrow in GridView1.Rows)
        {
            //gvrow.BackColor = Color.White;
            if (j <= GridView1.Rows.Count)
            {
                if (j % 2 != 0)
                {
                    for (int k = 0; k < gvrow.Cells.Count; k++)
                    {
                        gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
                    }
                }
            }
            j++;
        }
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();

    }
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        GridView1.AllowPaging = false;
        bindgrid();
        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Registration.doc"));
        Response.Charset = "";
        Response.ContentType = "application/ms-word";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();

    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
    protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
    {
        Download();
    }

    public void Download()
    {
        string filename = "reg.pdf";

        // string filename = "Filename/reg";
        PdfPTable table = new PdfPTable(9);
        table.WidthPercentage = 95;
        int[] wth_tab = { 5, 15, 15, 15, 15, 15, 15, 15, 15 };
        table.SetWidths(wth_tab);
        table.SpacingBefore = 90;
        table.SpacingAfter = 90;

        PdfPCell cell = null;

        cell = new PdfPCell(new Phrase(new Chunk("UID ", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.BOLD, BaseColor.WHITE))));
        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        cell.BackgroundColor = BaseColor.BLUE;
        table.AddCell(cell);
        cell.Colspan = 0;
        cell.Border = 1;
        //cell.BackgroundColor = System.Drawing.Color.Blue;

        cell = new PdfPCell(new Phrase(new Chunk("Date", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.BOLD, BaseColor.WHITE))));
        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        cell.BackgroundColor = BaseColor.BLUE;
        table.AddCell(cell);
        cell.Colspan = 0;
        cell.Border = 1;

        cell = new PdfPCell(new Phrase(new Chunk("Name", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.BOLD, BaseColor.WHITE))));
        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        cell.BackgroundColor = BaseColor.BLUE;
        table.AddCell(cell);
        cell.Colspan = 0;
        cell.Border = 1;

        cell = new PdfPCell(new Phrase(new Chunk("Organization", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.BOLD, BaseColor.WHITE))));
        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        cell.BackgroundColor = BaseColor.BLUE;
        table.AddCell(cell);
        cell.Colspan = 0;
        cell.Border = 1;

        cell = new PdfPCell(new Phrase(new Chunk("Designation", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.BOLD, BaseColor.WHITE))));
        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        cell.BackgroundColor = BaseColor.BLUE;
        table.AddCell(cell);
        cell.Colspan = 0;
        cell.Border = 1;

        cell = new PdfPCell(new Phrase(new Chunk("Contact No.", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.BOLD, BaseColor.WHITE))));
        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        cell.BackgroundColor = BaseColor.BLUE;
        table.AddCell(cell);
        cell.Colspan = 0;
        cell.Border = 1;

        cell = new PdfPCell(new Phrase(new Chunk("Mobile", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.BOLD, BaseColor.WHITE))));
        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        cell.BackgroundColor = BaseColor.BLUE;
        table.AddCell(cell);
        cell.Colspan = 0;
        cell.Border = 1;


        cell = new PdfPCell(new Phrase(new Chunk("City", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.BOLD, BaseColor.WHITE))));
        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        cell.BackgroundColor = BaseColor.BLUE;
        table.AddCell(cell);
        cell.Colspan = 0;
        cell.Border = 1;

        cell = new PdfPCell(new Phrase(new Chunk("EmailID", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.BOLD, BaseColor.WHITE))));
        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        cell.BackgroundColor = BaseColor.BLUE;
        table.AddCell(cell);
        cell.Colspan = 0;
        cell.Border = 1;

        string sql = "select * from msppt_com_impact.ASAXPartnerEDM_Reg order by id asc";
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int j = 0;

                cell = new PdfPCell(new Phrase(new Chunk("" + dt.Rows[i]["id"].ToString() + "", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.NORMAL))));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                j = i % 2;
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                if (j == 0)
                    cell.BackgroundColor = BaseColor.WHITE;



                table.AddCell(cell);

                cell.Colspan = 0;
                cell.Border = 1;
                //cell.BackgroundColor = System.Drawing.Color.Blue;

                //cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                //table.AddCell(cell);

                string dtt = Convert.ToDateTime(dt.Rows[i]["in_ts"]).ToString("dd/MM/yyyy");

                cell = new PdfPCell(new Phrase(new Chunk("" + dtt + "", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.NORMAL))));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                j = i % 2;
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                if (j == 0)
                    cell.BackgroundColor = BaseColor.WHITE;
                table.AddCell(cell);
                cell.Colspan = 0;
                cell.Border = 1;


                cell = new PdfPCell(new Phrase(new Chunk("" + dt.Rows[i]["name"].ToString() + "", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.NORMAL))));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                j = i % 2;
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                if (j == 0)
                    cell.BackgroundColor = BaseColor.WHITE;
                table.AddCell(cell);
                cell.Colspan = 0;
                cell.Border = 1;


                cell = new PdfPCell(new Phrase(new Chunk("" + dt.Rows[i]["organization"].ToString() + "", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.NORMAL))));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                j = i % 2;
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                if (j == 0)
                    cell.BackgroundColor = BaseColor.WHITE;
                table.AddCell(cell); cell.Colspan = 0;
                cell.Border = 1;


                cell = new PdfPCell(new Phrase(new Chunk("" + dt.Rows[i]["designation"].ToString() + "", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.NORMAL))));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                j = i % 2;
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                if (j == 0)
                    cell.BackgroundColor = BaseColor.WHITE;
                table.AddCell(cell); cell.Colspan = 0;
                cell.Border = 1;


                cell = new PdfPCell(new Phrase(new Chunk("" + dt.Rows[i]["contactno"].ToString() + "", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.NORMAL))));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                j = i % 2;
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                if (j == 0)
                    cell.BackgroundColor = BaseColor.WHITE;
                table.AddCell(cell); cell.Colspan = 0;
                cell.Border = 1;

                cell = new PdfPCell(new Phrase(new Chunk("" + dt.Rows[i]["mobile"].ToString() + "", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.NORMAL))));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                j = i % 2;
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                if (j == 0)
                    cell.BackgroundColor = BaseColor.WHITE;
                table.AddCell(cell); cell.Colspan = 0;
                cell.Border = 1;

                cell = new PdfPCell(new Phrase(new Chunk("" + dt.Rows[i]["tbmname"].ToString() + "", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.NORMAL))));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                j = i % 2;
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                if (j == 0)
                    cell.BackgroundColor = BaseColor.WHITE;
                table.AddCell(cell); cell.Colspan = 0;
                cell.Border = 1;

                cell = new PdfPCell(new Phrase(new Chunk("" + dt.Rows[i]["email"].ToString() + "", FontFactory.GetFont("Verdana", 8, iTextSharp.text.Font.NORMAL))));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                j = i % 2;
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                if (j == 0)
                    cell.BackgroundColor = BaseColor.WHITE;
                table.AddCell(cell); cell.Colspan = 0;
                cell.Border = 1;

            }
        }


        StringWriter sw = new StringWriter();
        HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
        string html = sw.ToString();
        float ml = 10.1f;
        float mr = 10.1f;
        float mt = 20.1f;
        float mb = 10.1f;
        Document Doc = new Document(PageSize.A4, ml, mr, mt, mb);
        Doc.SetPageSize(iTextSharp.text.PageSize.A4);
        //PdfWriter.GetInstance(Doc, new FileStream(System.IO.Path.GetFullPath(Server.MapPath(filename)), FileMode.Create));
        PdfWriter.GetInstance(Doc, new FileStream(System.IO.Path.GetFullPath(Server.MapPath("./Filename/" + filename)), FileMode.Create));

        Doc.Open();
        //Doc.Add(new Paragraph("JPG"));
       // string url = "https://impactmarketingservice.co.in/ciscobangaloreevent/header.jpg";
       // iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(new Uri(url));
        //jpg.Alignment = iTextSharp.text.Image.ALIGN_LEFT;
        //jpg.ScalePercent(70);
        //Doc.Add(jpg);
        //Doc.Add(new Paragraph(""));

        Doc.Add(table);

        System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(new StringReader(html));

        Paragraph p1 = new Paragraph(new Chunk("NEW PAGE TEST", FontFactory.GetFont("Verdana", 8)));

        xmlReader = new System.Xml.XmlTextReader(new StringReader(html));
        Doc.Close();

        string Path = Server.MapPath("./Filename/" + filename);
        //string fname = "reg.pdf";
        //string Path = Server.MapPath(filename);
        ShowPdf(filename);

        DownloadFile(filename, true);


    }


    public void ShowPdf(string arg)
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + arg);
       
        string Path = Server.MapPath("./Filename/" + arg);

        //string Path = Server.MapPath(arg);

        Response.TransmitFile(Path);
        Response.End();
        Response.Flush();
        Response.Clear();
    }
    public void DownloadFile(string fname, bool forceDownload)
    {
        string path = MapPath(fname);
        string name = Path.GetFileName(path);
        string ext = Path.GetExtension(path);
        string type = "";
        if (ext != null)
        {
            switch (ext.ToLower())
            {
                case ".htm":
                case ".html":
                    type = "text/HTML";
                    break;

                case ".txt":
                    type = "text/plain";
                    break;

                case ".doc":
                case ".rtf":
                    type = "Application/msword";
                    break;
                case ".pdf":
                    type = "Application/pdf";
                    break;
            }
        }
        if (forceDownload)
        {
            Response.AppendHeader("content-disposition", "attachment; filename=" + name);
        }
        if (type != "")
            Response.ContentType = type;

        Response.WriteFile(path);
        Response.End();
    }
 }

No comments:

Post a Comment