Hossein Zahed

Web Developer, Entrepreneur, Software Educator

How to Export Gridview to PDF in asp.net and C#

1. Add the following method to the code behind of the page:

public override void VerifyRenderingInServerForm(Control control)
    {

    }

2. Download the Attached DLL file called iTextSharp.dll

3. Reference the iTextSharp.dll by adding it to the Bin folder of the website.

4. Add the following NameSpaces to the code behind page:

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

4. Add the following codes on the Post Back action of a button on the page:

protected void GeneratePDFBtn_Click(object sender, EventArgs e)
    {
        gvDataBind(FileNameHF.Value.ToString()); 
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", Guid.NewGuid() + ".pdf"));
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        gv.AllowPaging = false;
        gv.DataBind();
        gv.RenderControl(hw);
        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);
        pdfDoc.Open();
        htmlparser.Parse(sr); pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End(); 
    }

Download: itextsharp-dll-core.zip (1.68 mb)

How to Export Gridview to Excel in asp.net and C#

1. Add the following method to the code behind of the page:

public override void VerifyRenderingInServerForm(Control control)
    {

    }

2. Add the following codes on the Post Back action of a button on the page:

protected void GenerateExcelBtn_Click(object sender, EventArgs e)
    {
        GridView1.DataBind();
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", Guid.NewGuid() + ".xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        gv.AllowPaging = false; gv.DataBind();
        gv.HeaderRow.Style.Add("background-color", "#FFFFFF");
        gv.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }