Thursday, April 23, 2015

[ASP.NET] Export to Word, PDF, Excel File

Bạn muốn lập trình cho phép Export dữ liệu từ Datatable, Gridview ra Excel, Word hay PDF? Trong bài viết này mình giới thiệu và sử dụng thư viện itextsharp.dll.
Library và Example : 
https://drive.google.com/folderview?id=0BxebKjwCwomqaDhTTlZacmtwbGc&usp=sharing 

Code example: 
/// 
/// Export GridView to Word
/// 
private void ExporttoWord(GridView Gridviewname)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=WordExport.doc");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-word ";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    // Paging Allow
    Gridviewname.AllowPaging = false;
    Gridviewname.DataBind();
    Gridviewname.RenderControl(hw);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}



/// 
/// Export GridView to PDF
/// 
private void ExporttoPDF(GridView Gridviewname)
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=PDFExport.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    Gridviewname.AllowPaging = false;
    Gridviewname.DataBind();
    Gridviewname.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();  
}


/// 
/// Export GridView to Excel
/// 
private void ExporttoExcel(GridView Gridviewname)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
     "attachment;filename=ExcelExport.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    // Paging Allow
    Gridviewname.AllowPaging = false;
    Gridviewname.DataBind();
    Gridviewname.RenderControl(hw);
    // Format
    string style = @"";
    Response.Write(style);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

No comments:

Bài đăng phổ biến