News Ticker

Menu

Cho phép chọn cột và sử dụng itextsharp để Export danh sách dữ liệu ra PDF trên Datalist

(Export các cột được chọn trong Asp.net sử dụng thư viện iTextSharp) - Bài viết dưới đây, thủ thuật tin học sẽ giới thiệu với các bạn cách sử dụng thư viện iTextSharp để Export danh sách dữ liệu (Datatable) cho phép lựa chọn cột dữ liệu ra file PDF. Chương trình sẽ tự động lấy toàn bộ các trường dữ liệu có trong 1 bảng dữ liệu, người dùng có thể chọn hoặc bỏ chọn những trường không cần thiết để Export ra file PDF.
Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube




Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



- B1: Download CSDL Northwind  tại đây và thực hiện công việc Restore Data.

- B2: Tạo Project trong Microsoft Visual Studio 2010

Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.IO;
using System.Text;
using System.Web;

namespace ExportSelectedColumnsUsingItextsharp
{
    public class SqlDataProvider
    {
        #region "Membres Prives"

        private string _connectionString;

        #endregion

        #region "Constructeurs"

        public SqlDataProvider()
        {
            try
            {
                _connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
            }
            catch
            {
            }
        }

        #endregion

        #region "Proprietes"

        public string ConnectionString
        {
            get { return _connectionString; }
        }

        #endregion

        #region "Functions"

        public DataTable FillTable(string sql)
        {
            try
            {
                DataTable tb = new DataTable();
                SqlDataAdapter adap = new SqlDataAdapter(sql, _connectionString);
                adap.Fill(tb);
                return tb;
            }
            catch
            {
                return null;
            }
        }

        #endregion
    }

    public class MyEventArgs : EventArgs
    {

        private string Name;

        private string MyId;
        public string SelectedName
        {
            get { return Name; }
            set { Name = value; }
        }

        public string Id
        {
            get { return MyId; }
            set { MyId = value; }
        }
    }

    public class Constants
    {
        public const string DEFAULT_COLOR_COMPANYNAME = "#007dc2";
        public const string DEFAULT_BACKGROUNDCOLOR_HEADERROW = "#99cd00";
        public const string DEFAULT_COLOR_HEADERROW = "#ffffff";
        public const string DEFAULT_BORDERCOLOR_TABLE = "#808080";
        public const string DEFAULT_BACKGROUNDCOLOR_ROW = "#edf5ff";
    }
}

Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config

B3: Download  thư viện iTextSharp tại đây

B4: References  itextsharp.dll trong thư mục vừa giải nén vào Project

B5: Tạo thư mục Fonts,  Download Font ARIALUNI.TTF tại đây và  copy file này vào thư mục vừa tạo.

B6: Download  thư viện AjaxControlToolkit tại địa chỉ: http://ajaxcontroltoolkit.codeplex.com/downloads/get/116534

B7: Giải nén AjaxControlToolkit.Binary.NET4, và References Ajaxcontroltoolkit.dll trong thư mục vừa giải nén vào Project.

B8: Tạo thư mục UserControls, thêm file Popup_SelectedColumns.ascx và nhập mã HTML
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Popup_SelectedColumns.ascx.cs" Inherits="ExportSelectedColumnsUsingItextsharp.UserControls.Popup_SelectedColumns" %>
<%@ Register TagPrefix="cc1" Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" %>
<script language="javascript" type="text/javascript">
    function CheckBoxListSelect(cbControl, state) {
        var chkBoxList = document.getElementById(cbControl);
        var chkBoxCount = chkBoxList.getElementsByTagName("input");
        for (var i = 0; i < chkBoxCount.length; i++) {
            chkBoxCount[i].checked = state;
        }
        return false;
    }
</script>

<asp:Panel ID="pnlpopup" runat="server" style="display:none">
    <asp:UpdatePanel ID="updatePanelPopup" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Button id="cmdShowPopup" runat="server" style="display:none" />
            <cc1:ModalPopupExtender ID="ModalPopupExtender_Popup" runat="server" TargetControlID="cmdShowPopup" X="750" Y="150"
                PopupControlID="pnlpopup" CancelControlID="cmdCancel" BackgroundCssClass="ModalPopupBG" Drag="True" />
                <div class="modal" style="width:450px;">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" id="cmdClose" runat="server" causesvalidation="false" onserverclick="cmdClose_ServerClick" class="close" data-dismiss="modal" aria-hidden="true">x</button>
                                <h4 class="modal-title">
                                    <asp:label id="lblHeader" runat="server" Text="Export only selected columns to PDF"></asp:label>
                                </h4>
                              </div>
                              <div class="modal-body">
                                   <table width="100%" cellpadding="0" cellspacing="0">
                                       <tr>
                                            <td style="padding-left:10px;padding-bottom:5px;">
                                                 <a id="A1" href="#" onclick="javascript: CheckBoxListSelect ('<%= chkExport.ClientID %>',true)">
                                                       <asp:label id="plCheckAll" runat="server" CssClass="NormalBold" text="CheckAll"></asp:label>
                                                  </a>|
                                                  <a id="A2" href="#" onclick="javascript: CheckBoxListSelect ('<%= chkExport.ClientID %>',false)">
                                                       <asp:label id="plUnCheckAll" runat="server" CssClass="NormalBold" text="UnCheckAll"></asp:label>
                                                  </a>
                                            </td>
                                       </tr>
                                       <tr>
                                           <td>
                                               <asp:CheckBoxList ID="chkExport" CellPadding="5" CellSpacing="10" RepeatColumns="2" runat="server">
                                               </asp:CheckBoxList>
                                           </td>
                                       </tr>
                                   </table>
                              </div>
                              <div class="modal-footer">
                                   <div class="btn-group">
                                        <asp:LinkButton id="cmdOK" runat="server" OnClick="cmdOK_Click" CssClass="btn btn-small" CausesValidation="false">
                                            <i class="icon-exportpdf"></i>&nbsp;&nbsp;<asp:label id="lblExport" runat="server" Text="Export"></asp:label>
                                        </asp:LinkButton>&nbsp;
                                         <asp:LinkButton id="cmdCancel" runat="server" OnClick="cmdCancel_Click" CssClass="btn btn-small" Causesvalidation="false">
                                            <i class="icon-close"></i>&nbsp;&nbsp;<asp:label id="lblClose" runat="server" Text="Close"></asp:label>
                                        </asp:LinkButton>
                                   </div>
                              </div>
                        </div>
                    </div>
                </div>
        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="cmdOK" />
        </Triggers>
    </asp:UpdatePanel>   
</asp:Panel>   
B13: Nhập Code phía dưới cho file Popup_SelectedColumns.ascx
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;

namespace ExportSelectedColumnsUsingItextsharp.UserControls
{
    partial class Popup_SelectedColumns : System.Web.UI.UserControl
    {

        #region "Private Members"

        private int _ItemID;
        private string _ItemName;

        #endregion

        #region "Event Click"

        public delegate void MyEventHandler(object sender, MyEventArgs e);
        public event MyEventHandler OnSelectedRow;

        #endregion

        #region "Private Methods"

        private IEnumerable<string> GetColumnNames(string TableName)
        {
            dynamic ColumnNames = new List<string>();
            SqlDataProvider objSQL = new SqlDataProvider();
            DataTable objBind = objSQL.FillTable("Select COLUMN_NAME, DATA_TYPE FROM information_schema.columns where TABLE_NAME ='" + TableName + "'");

            if (objBind != null)
            {
                foreach (DataRow row in objBind.Rows)
                {
                    ColumnNames.Add(row.Field<string>("COLUMN_NAME"));
                }
            }
            return ColumnNames;
        }

        #endregion

        #region "GetColumnNames"

        private void BindColumn()
        {
            string TableName = "Products";
            dynamic ColumnNames = GetColumnNames(TableName);
            int i = 0;
            chkExport.Items.Clear();
            foreach (string columnName in ColumnNames)
            {
                chkExport.Items.Add(new System.Web.UI.WebControls.ListItem(columnName, columnName));
                chkExport.Items[i].Selected = true;
                i = i + 1;
            }
        }

        #endregion

        #region "Pulbic Methods"

        public void ShowPopup(int ItemID)
        {
            BindColumn();
            updatePanelPopup.Update();
            ModalPopupExtender_Popup.Show();
        }

        public void HidePopup()
        {
            ModalPopupExtender_Popup.Hide();
        }

        #endregion

        #region "Properties"

        public int ItemID
        {
            get { return _ItemID; }
            set { _ItemID = value; }
        }

        public string ItemName
        {
            get { return _ItemName; }
            set { _ItemName = value; }
        }

        #endregion

        #region "Event Handles"

        protected void cmdOK_Click(object sender, System.EventArgs e)
        {
            MyEventArgs MyArgs = new MyEventArgs();
            string sListExport = "";
            int i = 0;
            int iCount = 0;

            for (i = 0; i <= chkExport.Items.Count - 1; i++)
            {
                if (chkExport.Items[i].Selected)
                {
                    sListExport += chkExport.Items[i].Value + ",";
                    iCount = iCount + 1;
                }
            }

            if (sListExport.Length > 0 & sListExport.EndsWith(","))
            {
                sListExport = sListExport.Remove(sListExport.Length - 1, 1);
            }

            ModalPopupExtender_Popup.Hide();

            MyArgs.Id = sListExport;
            MyArgs.SelectedName = iCount.ToString();
            if (OnSelectedRow != null)
            {
                OnSelectedRow(this, MyArgs);
            }
        }

        protected void cmdCancel_Click(object sender, System.EventArgs e)
        {
            ModalPopupExtender_Popup.Hide();
        }

        protected void cmdClose_ServerClick(object sender, System.EventArgs e)
        {
            ModalPopupExtender_Popup.Hide();
        }

        #endregion
    }
}

B11: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
<%@ Page Title="Export Selected Columns Using itextsharp in ASP.Net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExportSelectedColumnsUsingItextsharp._Default" %>
<%@ Register TagPrefix="ModalPopup" TagName="Export" Src="~/UserControls/Popup_SelectedColumns.ascx"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
        Export Selected Columns Using itextsharp in Datalist ASP.Net
    </h3>
    <ModalPopup:Export ID="ucSelectedColumns" runat="server" />
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2" cellspacing="3" width="100%">
                <tr>
                    <td>
                        <div class="btn-group">
                            <asp:LinkButton id="cmdExport" runat="server" OnClick="cmdExport_Click" CssClass="btn btn-small" Causesvalidation="false">
                                <i class="icon-exportpdf"></i>&nbsp;&nbsp;<asp:label id="lblExport" runat="server" Text="ExportToPDF"></asp:label>
                            </asp:LinkButton>
                        </div>
                    </td>
                </tr>
                <tr id="trMessage" runat="server" visible="false">
                    <td>
                        <asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:DataList ID="dlObject" runat="server" DataKeyField="ProductID" Width="100%">
                            <HeaderStyle CssClass="GridStyle_HeaderStyle" />
                            <ItemStyle CssClass="GridStyle_RowStyle" />
                            <HeaderTemplate>
                            <table cellpadding="0" cellspacing="0" width="100%">
                                <tr>
                                    <th align="center" width="20px">
                                        <asp:CheckBox ID="chkAll" runat="server" />
                                    </th>
                                    <th colspan="5">
                                        <table id="tblProduct" runat="server" cellpadding="0" cellspacing="0" width="100%">
                                            <tr>
                                                <th align="center" width="200">ProductName</th>
                                                <th align="center" width="100">QuantityPerUnit</th>
                                                <th align="center" width="80">UnitPrice</th>
                                                <th align="center" width="80">UnitsInStock</th>
                                                <th align="center" width="80">UnitsOnOrder</th>       
                                            </tr>
                                        </table>
                                    </th>             
                                </tr>
                            </HeaderTemplate>
                            <ItemTemplate>
                                <tr>
                                    <td colspan="6">
                                        <table id="tblInfo" runat="server" cellpadding="0" cellspacing="0" width="100%">
                                            <tr>
                                                <td align="center" width="20px">
                                                    <asp:CheckBox ID="chkSelect" runat="server" />
                                                </td>
                                                <td align="left" width="200"><%# Eval("ProductName") %></td>
                                                <td align="left" width="100"><%# Eval("QuantityPerUnit") %></td>
                                                <td align="right" width="80"><%# Eval("UnitPrice") %></td>
                                                <td align="right" width="80"><%# Eval("UnitsInStock") %></td>
                                                <td align="right" width="80"><%# Eval("UnitsOnOrder") %></td>       
                                            </tr>
                                        </table>
                                    </td>             
                                </tr>
                            </ItemTemplate>
                            <FooterTemplate>
                            </table>
                            </FooterTemplate>
                        </asp:DataList>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="cmdExport" />
        </Triggers>
    </asp:UpdatePanel>
</asp:Content>
B12: Viết Code cho file Default.aspx
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Data;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web;
using iTextSharp.text.html;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

namespace ExportSelectedColumnsUsingItextsharp
{
    public partial class _Default : System.Web.UI.Page
    {
        #region "Export PDF"

        private void MySelExport_OnSelectedRow(object sender, ExportSelectedColumnsUsingItextsharp.MyEventArgs e)
        {
            string sExportList = "";
            int iCount = 0;
            var _with1 = e;
            if (!string.IsNullOrEmpty(e.Id))
            {
                sExportList = e.Id;
                iCount =Convert.ToInt32(e.SelectedName);
                if (!string.IsNullOrEmpty(sExportList))
                {
                    ExportToPDF("List-Product.pdf", sExportList, iCount);
                }
            }
        }

        private void ExportToPDF(string FileName, string ExportList, int iCount)
        {
            Document document = new Document(PageSize.A4, 10f, 10f, 5f, 0f);
            System.IO.MemoryStream msReport = new System.IO.MemoryStream();
            string FilePath = "";

            FilePath = Server.MapPath("Fonts\\ARIALUNI.TTF");
            string fontpath = FilePath;
            BaseFont bf = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font fontCompany = new Font(bf, 13, Font.BOLD, new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_COMPANYNAME)));
            Font fontHeader = new Font(bf, 12, Font.BOLD, Color.BLUE);
            Font fontSubHeader = new Font(bf, 10);
            Font fontTitle = new Font(bf, 11, Font.BOLD, Color.BLACK);
            Font fontContent = new Font(bf, 11, Font.NORMAL, Color.BLACK);
            Font fontTableHeader = new Font(bf, 10, Font.BOLD, new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_HEADERROW)));

            try
            {
                PdfWriter writer = PdfWriter.GetInstance(document, msReport);
                document.AddAuthor("Thu thuat lap trinh");
                document.AddSubject("Export to PDF");

                document.Open();

                Chunk cBreak = new Chunk(Environment.NewLine);
                Phrase pBreak = new Phrase();
                Paragraph paBreak = new Paragraph();

                //=================Start Header =====================
                //CompnayName
                string sText = "THỦ THUẬT LẬP TRÌNH";
                Chunk beginning = new Chunk(sText, fontCompany);
                Phrase p1 = new Phrase(beginning);
                Paragraph pCompanyName = new Paragraph();
                pCompanyName.IndentationLeft = 30;
                pCompanyName.Add(p1);
                document.Add(pCompanyName);

                //Website
                string sWebsite = "Website: http://www.laptrinhdotnet.com";
                sText = "";
                if (!string.IsNullOrEmpty(sWebsite))
                {
                    sText = sWebsite;
                }

                if (!string.IsNullOrEmpty(sText))
                {
                    sText = sText.Replace(Environment.NewLine, string.Empty).Replace("  ", string.Empty);
                    beginning = new Chunk(sText, fontSubHeader);
                    p1 = new Phrase(beginning);
                    Paragraph pAddresse = new Paragraph();
                    pAddresse.IndentationLeft = 30;
                    pAddresse.Add(p1);
                    document.Add(pAddresse);
                }

                string sEmail = "Email: kenhphanmemviet@gmail.com";
                if (!string.IsNullOrEmpty(sEmail))
                {
                    sText = sEmail;
                }

                if (!string.IsNullOrEmpty(sText))
                {
                    sText = sText.Replace(Environment.NewLine, string.Empty).Replace("  ", string.Empty);
                    beginning = new Chunk(sText, fontSubHeader);
                    p1 = new Phrase(beginning);
                    Paragraph pAddresse = new Paragraph();
                    pAddresse.IndentationLeft = 30;
                    pAddresse.Add(p1);
                    document.Add(pAddresse);
                }
                //=================End Header =====================

                //Title
                sText = "LIST PRODUCT" + Environment.NewLine;
                if (!string.IsNullOrEmpty(sText))
                {
                    beginning = new Chunk(sText, fontHeader);
                    p1 = new Phrase(beginning);
                    Paragraph pAddresse = new Paragraph();
                    pAddresse.IndentationLeft = 10;
                    pAddresse.Alignment = 1;
                    pAddresse.Add(p1);
                    document.Add(pAddresse);
                }

                iTextSharp.text.Table datatable = new iTextSharp.text.Table(iCount);
                datatable.Padding = 2;
                datatable.Spacing = 1;
                datatable.WidthPercentage = 98;

                float[] headerwidths = new float[iCount];
                int x = 0;
                int ItemStyleWidth = 10;
                ItemStyleWidth = 100 / iCount;
                foreach (string sValue in ExportList.Split(','))
                {
                    //Header Table
                    headerwidths[x] = Convert.ToInt32(ItemStyleWidth);
                    Cell cellText = new Cell(new Phrase(sValue, fontTableHeader));
                    cellText.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BACKGROUNDCOLOR_HEADERROW));
                    cellText.HorizontalAlignment = 1;
                    cellText.VerticalAlignment = 1;
                    datatable.AddCell(cellText);
                    x = x + 1;
                }
                datatable.Widths = headerwidths;
                datatable.BorderWidth = 1;
                datatable.DefaultCellBorderWidth = 1;
                datatable.DefaultHorizontalAlignment = 1;
                datatable.DefaultVerticalAlignment = 1;
                datatable.DefaultCellBorderColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BORDERCOLOR_TABLE));
                datatable.BorderColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BORDERCOLOR_TABLE));

                DataTable objBind = new DataTable();
                DataColumn dColumn = null;
                objBind = BindData();

                if (objBind != null)
                {
                    if (objBind.Rows.Count > 0)
                    {
                        foreach (DataRow row in objBind.Rows)
                        {
                            {
                                if (row != null)
                                {
                                    foreach (string sValue in ExportList.Split(','))
                                    {
                                        foreach (DataColumn dColumn_loopVariable in objBind.Columns)
                                        {
                                            dColumn = dColumn_loopVariable;
                                            if (sValue == dColumn.ColumnName)
                                            {
                                                datatable.DefaultHorizontalAlignment = Element.ALIGN_LEFT;
                                                datatable.AddCell(new Phrase(row[sValue].ToString(), fontContent));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        document.Add(datatable);
                    }
                }
            }
            catch
            {
            }
            document.Close();
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".pdf");
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(msReport.ToArray());
            Response.End();
        }

        #endregion

        #region "Bind Data"

        private void BindProduct()
        {
            DataTable objBind = new DataTable();
            objBind = BindData();

            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    dlObject.DataSource = objBind;
                    dlObject.DataBind();
                    trMessage.Visible = false;
                    dlObject.Visible = true;
                }
                else
                {
                    trMessage.Visible = true;
                    dlObject.Visible = false;
                }
                updatePanel.Update();
            }
        }

        private DataTable BindData()
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataTable objBind = objSQL.FillTable("Select Products.* From Products");
            return objBind;
        }

        #endregion

        #region "Event Handles"

        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                ((ExportSelectedColumnsUsingItextsharp.UserControls.Popup_SelectedColumns)ucSelectedColumns).OnSelectedRow += MySelExport_OnSelectedRow;
                if (!IsPostBack)
                {
                    BindProduct();
                }
            }
            catch
            {
            }
        }

        protected void cmdExport_Click(object sender, System.EventArgs e)
        {
            var ucSelected = (ExportSelectedColumnsUsingItextsharp.UserControls.Popup_SelectedColumns)ucSelectedColumns;
            ucSelected.ShowPopup(-1);
        }

        #endregion
    }
}

Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



Chúc các bạn thành công!

Quang Bình

Share This:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Cho phép chọn cột và sử dụng itextsharp để Export danh sách dữ liệu ra PDF trên Datalist "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM