(Làm thế nào để xuất dữ liệu Gridview sang PDF trong Asp.net) – Trong một số trường hợp, người sử dụng không muốn Export toàn bộ các cột trong danh sách dữ liệu mà chỉ muốn Export toàn bộ dữ liệu đã được hiển thị trên Gridview ra file Excel. Bài viết dưới đây sẽ hướng dẫn các bạn làm công việc này.
- B1: Tạo CSDL SQL Customers
- B2: Tạo Bảng Accounts có cấu trúc phía dưới trong CSDL SQL Server
STT | Tên trường | Kiểu trường | Ghi chú |
1 | AccountID | Int | Trường tự tăng |
2 | AccountCode | nvarchar(25) | |
3 | AccName | nvarchar(250) | |
4 | AccAddress | nvarchar(250) | |
5 | AccPhone | nvarchar(50) | |
6 | AccFAX | nvarchar(50) | |
7 | AccEmail | nvarchar(50) | |
8 | AccWebsite | nvarchar(150) | |
9 | AccDesc | nvarchar(1500) | |
10 | CreatedDate | datetime | |
11 | ModifiedDate | datetime |
- B3: Nhập dữ liệu cho bảng Accounts
- B4: Tạo các stored procedure trong SQL Server
USE [Customers]
GO
CREATE PROCEDURE [dbo].[Pro_Accounts_Get]
@AccountID int
AS
SELECT * FROM Accounts
WHERE
AccountID = @AccountID
Go
CREATE PROCEDURE [dbo].[Pro_Accounts_List]
@Keyword nvarchar(250),
@SortField nvarchar(50),
@SortType nvarchar(10)
AS
declare @strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'Select * from Accounts'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (AccountCode like N''%' +@Keyword+'%''
Or AccName like N''%' +@Keyword+'%'' Or AccAddress like N''%' +@Keyword+'%''
Or AccPhone like N''%' +@Keyword+'%'' Or AccFAX like N''%' +@Keyword+'%''
Or AccEmail like N''%' +@Keyword+'%'' Or AccWebsite like N''%' +@Keyword+'%'')'
if @SortField='CreatedDate'
Begin
set @strOrder =' Order by CreatedDate'
End
Else
Begin
set @strOrder =' Order by AccName'
End
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
Go
- B5: 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.
Imports System.Data.SqlClient
Imports System.Data
Namespace ExportGridviewToExcel
Public Class SqlDataProvider
#Region "Membres Prives"
Shared _IsError As Boolean = False
Private _connectionString AsString
#End Region
#Region "Constructeurs"
Public Sub New()
Try
_connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
_IsError = False
Catch ex As Exception
_IsError = True
End Try
End Sub
#End Region
#Region "Proprietes"
Public ReadOnly Property ConnectionString() AsString
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public FunctionFillTable(ByVal sql AsString) As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(sql, _connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
Public FunctionFillTable(ByVal ProcName As String, ByVal ParamArrayPara() As ObjectPara) As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
If NotPara Is NothingThen
For Eachp As ObjectParaIn Para
adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
End If
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
Public FunctionRunSQL(ByVal ProcName AsString, ByVal ParamArray Para() As ObjectPara) As Object
Try
Dim _cnn AsNew SqlConnection(_connectionString)
_cnn.Open()
Dim cmd AsNew SqlCommand(ProcName, _cnn)
cmd.CommandType = CommandType.StoredProcedure
For Eachp As ObjectParaIn Para
cmd.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
Return cmd.ExecuteScalar
Catch ex As Exception
Return Nothing
End Try
End Function
#End Region
End Class
Public Class ObjectPara
Dim _name As String
Dim _Value As Object
Sub New(ByVal Pname As String, ByVal PValue As Object)
_name = Pname
_Value = PValue
End Sub
Public PropertyName() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public PropertyValue() As Object
Get
Return _Value
End Get
Set(ByVal value As Object)
_Value = value
End Set
End Property
End Class
Public Class MyEventArgs
Inherits EventArgs
Private Name As String
Private MyId As String
Public PropertySelectedName() As String
Get
ReturnName
End Get
Set(ByVal value As String)
Name = value
End Set
End Property
Public Property Id() As String
Get
Return MyId
End Get
Set(ByVal value As String)
MyId = value
End Set
End Property
End Class
Public Class Constants
Public ConstDEFAULT_BACKGROUNDCOLOR_HEADERROW As String = "#99cd00"
Public Const DEFAULT_COLOR_HEADERROW As String = "#ffffff"
Public ConstDEFAULT_BORDERCOLOR_TABLE As String = "#808080"
Public ConstDEFAULT_BACKGROUNDCOLOR_ROW As String = "#edf5ff"
End Class
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B6: Download các file ảnh tại đây, Copy ảnh lần lượt vào các thư mục Images
+ delete.gif, icon_search.gif vào thư mục Images
+ no.png, yes.png, sprite.png, lt.gif, icon_excel.png vào thư mục Styles\Images
- B7: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ PageTitle="Export Gridview to Excel in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb"Inherits="ExportGridviewToExcel._Default"%>
<%@ RegisterTagPrefix="ModalPopup"TagName="Delete"Src="~/UserControls/Popup_ConfirmDelete.ascx"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<h1>
Export Gridview to Excel in ASP.Net
</h1>
<br />
<ModalPopup:Delete ID="ucDeleteItem"runat="server"/>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%">
<tr>
<td>
<asp:LinkButton id="cmdExport" runat="server" CssClass="btn btn-small" Causesvalidation="false">
<i class="icon-exportexcel"></i> <asp:label id="lblExport" runat="server" Text="Export Excel"></asp:label>
</asp:LinkButton>
</td>
<tdalign="right">
<asp:Label ID="plKeyword" runat="server" Text="Keyword"></asp:Label>
<asp:TextBox ID="txtSearch" CssClass="form-control" ToolTip="Enter Keyword" runat="server" width="200px"></asp:TextBox>
<asp:ImageButton ID="cmdQuickSearch" runat="server" causesvalidation="false" imageurl="~/images/icon_search.gif"></asp:ImageButton>
</td>
</tr>
<trid="trMessage"runat="server"visible="false">
<tdcolspan="2">
<asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
</td>
</tr>
<tr>
<tdcolspan="2">
<asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="8"
CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
BorderWidth="1" AutoGenerateColumns="false" DataKeyNames="AccountID" width="100%">
<AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"/>
<RowStyle CssClass="GridStyle_RowStyle" />
<pagerstyle cssclass="GridStyle_pagination"/>
<Columns>
<asp:BoundField ItemStyle-Width="10%"DataField="AccountCode"HeaderText="AccountCode"/>
<asp:BoundField ItemStyle-Width="15%"DataField="AccName"HeaderText="AccountName"/>
<asp:BoundField ItemStyle-Width="10%"DataField="AccPhone"HeaderText="Phone"/>
<asp:BoundField ItemStyle-Width="10%"DataField="AccFAX"HeaderText="FAX"/>
<asp:BoundField ItemStyle-Width="15%"DataField="AccEmail"HeaderText="Email"/>
<asp:TemplateField HeaderText="Function">
<ItemStyle HorizontalAlign="Center"width="5%"/>
<ItemTemplate>
<asp:ImageButton ID="cmdDelete"CommandName="Delete"CommandArgument='<%# Eval("AccountID")%>' runat="server"ImageUrl="~/images/delete.gif"CausesValidation="False"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="cmdExport"/>
</Triggers>
</asp:UpdatePanel>
</asp:Content>
- B11: Viết Code cho file Default.aspx
Imports System.IO
Namespace ExportGridviewToExcel
Public Class _Default
Inherits System.Web.UI.Page
#Region "Export Excel"
Private SubExportToExcel(ByVal FileName As String)
Dim style As String = "<style> .textmode { } </style>"
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Dim i As Integer = 0
grvObject.AllowPaging = False
BindAccount()
'Header
For i = 0 TogrvObject.Columns.Count - 1
grvObject.HeaderRow.Cells(i).BackColor = System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BACKGROUNDCOLOR_HEADERROW)
grvObject.HeaderRow.Cells(i).ForeColor = System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_HEADERROW)
Next
grvObject.HeaderRow.Cells(5).Visible = False
For i = 0 TogrvObject.Rows.Count - 1
Dim row AsGridViewRow = grvObject.Rows(i)
row.BackColor = System.Drawing.Color.White
row.Attributes.Add("class", "textmode")
row.Cells(5).Visible = False
If i Mod2 <> 0 Then
For j AsInteger = 0 TogrvObject.Columns.Count - 1
row.Cells(j).Style.Add("background-color", Constants.DEFAULT_BACKGROUNDCOLOR_ROW)
Next
End If
Next
grvObject.RenderControl(hw)
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=" & FileName & ".xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Verifies that the control is rendered
End Sub
#End Region
#Region "Bind Data"
Private SubBindAccount()
Dim objBind As New DataTable
objBind = BindData()
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
grvObject.DataSource = objBind
grvObject.DataBind()
trMessage.Visible = False
grvObject.Visible = True
Else
trMessage.Visible = True
grvObject.Visible = False
End If
updatePanel.Update()
End If
End Sub
Private FunctionBindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Accounts_List", New ObjectPara("@Keyword", txtSearch.Text.Trim), _
New ObjectPara("@SortField", "CreatedDate"), _
New ObjectPara("@SortType", "DESC"))
Return objBind
End Function
#End Region
#Region "GridView Methods"
Private SubgrvObject_RowDeleting(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grvObject.RowDeleting
Dim ItemID As Integer = CType(grvObject.DataKeys(e.RowIndex).Value, Integer)
Dim ItemName As String = ""
If ItemID <> -1 Then
With CType(ucDeleteItem, ExportGridviewToExcel.UserControls.Popup_ConfirmDelete)
.ItemID = ItemID
.ShowPopup(ItemID, "")
End With
End If
End Sub
Private SubgrvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) HandlesgrvObject.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
'Delete
Dim cmdDelete AsImageButton = DirectCast(e.Row.FindControl("cmdDelete"), ImageButton)
If NotcmdDelete Is NothingThen
cmdDelete.ToolTip = "Delete Account"
End If
End If
End Sub
Private SubgrvObject_PageIndexChanging(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindAccount()
End Sub
#End Region
#Region "Popup"
Private SubMySelDelete_OnSelectedRow(ByVal sender As Object, ByVal e AsExportGridviewToExcel.MyEventArgs)
Dim ItemName As String = ""
With e
If e.Id <> "" Then
BindAccount()
End If
End With
End Sub
#End Region
#Region "Event Handles"
Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
Try
AddHandler CType(ucDeleteItem, ExportGridviewToExcel.UserControls.Popup_ConfirmDelete).OnSelectedRow, AddressOf MySelDelete_OnSelectedRow
If Page.IsPostBack = False Then
'Default Submit Button
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
BindAccount()
End If
Catch ex As Exception
End Try
End Sub
Private SubcmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdQuickSearch.Click
BindAccount()
End Sub
Private SubcmdExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdExport.Click
ExportToExcel("List-Account.xls")
End Sub
#End Region
End Class
End Namespace
Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment