Friday, May 11, 2012

Import Grid View Data to Excel or Pdf in Asp.net c#

 Import Grid View Data to Excel or Pdf  in Asp.net  c#
// Design
1 . Create 1 Grid View .
// Code Behind

1. Bind the Gridview
 Step2 :
// For Excel
// declare format
public string MsoFormats = "";
 
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
  
    Response.Clear();

    Response.AddHeader("content-disposition", "attachment;filename=GridView1.xls");

    Response.Charset = "";

    Response.ContentType = "application/vnd.xls";
    HttpContext.Current.Response.Write(this.MsoFormats);
    StringWriter StringWriter = new StringWriter();

    HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);

    GridView1.RenderControl(HtmlTextWriter);

    Response.Write(StringWriter.ToString());

    Response.End();



}

// For Pdf

 protected void btnPDF_Click(object sender, ImageClickEventArgs e)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            gvdetails.AllowPaging = false;
            gvdetails.DataBind();
            gvdetails.RenderControl(hw);
            gvdetails.HeaderRow.Style.Add("width", "15%");
            gvdetails.HeaderRow.Style.Add("font-size", "10px");
            gvdetails.Style.Add("text-decoration", "none");
            gvdetails.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
            gvdetails.Style.Add("font-size", "8px");
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            //string Path = Server.MapPath("~/Jaram PDF/") + "Sample.pdf";

            //PdfWriter.GetInstance(pdfDoc, new FileStream(Path, FileMode.Create));
            pdfDoc.Open();
          htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }

// add this Render Comtrol in Code Bhind

  public override void VerifyRenderingInServerForm(Control control)
        {
        }


Thanks ..
Regards
[ Sibi Elango]

No comments:

Post a Comment