Export danh sách dữ liệu (Datatable) ra Excel trong Asp.net
(Export dữ liệu trong Asp.net ra Excel) – Việc cho phép xuất dữ liệu ra Excel sẽ người dùng dễ dàng, thuận tiện và chủ động trong việc căn chỉnh, điều chỉnh, bổ xung định dạng cũng như thông tin. Do vậy lựa chọn Export danh sách dữ liệu ra file Excel luôn là lựa chọn hàng đầu đối với người dùng.
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 Export toàn bộ danh sách dữ liệu ra file Excel.
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 Export toàn bộ danh sách dữ liệu ra file Excel.
- 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 ExportDatatableToExcel
Public Class SqlDataProvider
#Region "Membres
Prives"
Shared _IsError As Boolean = False
Private _connectionString As
String
#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() As
String
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public Function
FillTable(ByVal sql As
String) As DataTable
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(sql,
_connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function
FillTable(ByVal ProcName As String, ByVal ParamArray
Para() As ObjectPara)
As DataTable
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(ProcName,
_connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
If Not
Para Is Nothing
Then
For Each
p As ObjectPara
In 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 Function
RunSQL(ByVal ProcName As
String, ByVal ParamArray Para() As ObjectPara) As Object
Try
Dim _cnn As
New SqlConnection(_connectionString)
_cnn.Open()
Dim cmd As
New SqlCommand(ProcName,
_cnn)
cmd.CommandType = CommandType.StoredProcedure
For Each
p As ObjectPara
In Para
cmd.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
Return cmd.ExecuteScalar
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function
GetRow(ByVal ProcName As
String, ByVal ParamArray Para() As ObjectPara) As DataRow
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(ProcName,
_connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
For Each
p As ObjectPara
In Para
adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
adap.Fill(tb)
If tb.Rows.Count Then
Return tb.Rows(0)
End If
Catch ex As Exception
Return Nothing
End Try
Return Nothing
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 Property
Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property
Value() 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 Property
SelectedName() As String
Get
Return Name
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
End Namespace
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.aspxdưới dạng HTML và nhập mã HTML
<%@ Page
Title="Export
Datatable To Excel in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ExportDatatableToExcel._Default" %>
<%@ Register
TagPrefix="ModalPopup"
TagName="ViewRecord"
Src="~/UserControls/Popup_ViewRecord.ascx"%>
<%@ Register
TagPrefix="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 Datatable To Excel in ASP.Net
</h1>
<br />
<ModalPopup:ViewRecord ID="ucViewRecord"
runat="server"
/>
<ModalPopup:Delete ID="ucDeleteItem"
runat="server"
/>
<asp:Label id="lblExportExcel"
runat="server"></asp:Label>
<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>
<td
align="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>
<tr
id="trMessage"
runat="server"
visible="false">
<td
colspan="2">
<asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
</td>
</tr>
<tr>
<td
colspan="2">
<asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="10"
CssClass="GridStyle"
BorderColor="#cbcbcb"
BorderStyle="solid"
BorderWidth="1"
AutoGenerateColumns="false"
DataKeyNames="AccountID"
width="100%">
<AlternatingRowStyle
CssClass="GridStyle_AltRowStyle"
/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<RowStyle CssClass="GridStyle_RowStyle"
/>
<pagerstyle cssclass="GridStyle_pagination"
/>
<Columns>
<asp:TemplateField HeaderText="AccountCode">
<ItemStyle width="6%" />
<ItemTemplate>
<asp:LinkButton id="cmdAccountCode"
runat="server"
CausesValidation="False"
CommandName="View"
CommandArgument='<%# Eval("AccountID") %>' text='<%# Eval("AccountCode") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AccountName">
<ItemStyle width="15%" />
<ItemTemplate>
<asp:LinkButton id="cmdAccountName"
runat="server"
CausesValidation="False"
CommandName="View"
CommandArgument='<%# Eval("AccountID") %>' text='<%# Eval("AccName") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblAccPhone"
Text='<%# Eval("AccPhone") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FAX">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblAccFAX"
Text='<%# Eval("AccFAX") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemStyle width="12%" />
<ItemTemplate>
<asp:Label ID="lblEmail"
Text='<%# Eval("AccEmail") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<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>
- B8: Viết Code cho file Default.aspx
Namespace ExportDatatableToExcel
Public Class _Default
Inherits System.Web.UI.Page
#Region "Export
Excel"
Private Function
InserHeaderInExcel() As String
Dim sExportToExcel As
String = ""
sExportToExcel &= "<table
border='0' cellpadding='0' cellspacing='0' width='99%' align='center'>"
& vbCrLf
sExportToExcel &= "<tr>"
& vbCrLf
sExportToExcel &= "<td
colspan='3' style='font-size:14pt;'><b>THỦ THUẬT LẬP TRÌNH</b></td>"
& vbCrLf
sExportToExcel &= "</tr>"
& vbCrLf
sExportToExcel &= "<tr>"
& vbCrLf
sExportToExcel &= "<td
colspan='3'><b>Website:</b>
http://thuthuatlaptrinh.blogspot.com</td>" & vbCrLf
sExportToExcel &= "</tr>"
& vbCrLf
sExportToExcel &= "<tr>"
& vbCrLf
sExportToExcel &= "<td
colspan='3'><b>Email:</b>
kenhphanmemviet@gmail.com</td>" & vbCrLf
sExportToExcel &= "</tr>"
& vbCrLf
sExportToExcel &= "</table>"
& vbCrLf
Return sExportToExcel
End Function
Private Function
ExportAccountToExcel(ByVal objBind As DataTable)
Dim sExportToExcel As
String = ""
Dim sActivitiesNumber As
String = ""
Dim sParentName As String = ""
Dim ListInfoContact As
String = ""
sExportToExcel &= "<div
id='div1'>" & vbCrLf
'=============Insert Header============
sExportToExcel &= InserHeaderInExcel()
'======================================
sExportToExcel &= "<table
border='0' cellpadding='0' cellspacing='0' width='99%' align='center'>"
& vbCrLf
sExportToExcel &= "<tr>"
& vbCrLf
sExportToExcel &= "<td
colspan='9'> </td>" & vbCrLf
sExportToExcel &= "</tr>"
& vbCrLf
sExportToExcel &= "<tr>"
& vbCrLf
sExportToExcel &= "<td
align='center' colspan='9' style='font-size:12pt;'><b>LIST
ACCOUNT</b></td>" & vbCrLf
sExportToExcel &= "</tr>"
& vbCrLf
sExportToExcel &= "<tr>"
& vbCrLf
sExportToExcel &= "<td
colspan='9'> </td>" & vbCrLf
sExportToExcel &= "</tr>"
& vbCrLf
sExportToExcel &= "</table>"
& vbCrLf
sExportToExcel &= "<table
border='1' cellpadding='0' cellspacing='0' width='99%' align='center'>"
& vbCrLf
sExportToExcel &= "<tr>"
& vbCrLf
sExportToExcel &= "<td
align='center'><b>AccountCode</b></td>" &
vbCrLf
sExportToExcel &= "<td
align='center'><b>AccountName</b></td>" &
vbCrLf
sExportToExcel &= "<td align='center'><b>Phone</b></td>"
& vbCrLf
sExportToExcel &= "<td
align='center'><b>FAX</b></td>" & vbCrLf
sExportToExcel &= "<td
align='center'><b>Email</b></td>" & vbCrLf
sExportToExcel &= "<td
align='center'><b>Website</b></td>" &
vbCrLf
sExportToExcel &= "<td
align='center'><b>Description</b></td>" &
vbCrLf
sExportToExcel &= "<td
align='center'><b>Created Date</b></td>" &
vbCrLf
sExportToExcel &= "<td
align='center'><b>Modified Date</b></td>"
& vbCrLf
sExportToExcel &= "</tr>"
& vbCrLf
'End Header
For Each row As DataRow In objBind.Rows
If Not
row Is Nothing Then
sExportToExcel &= "<tr>"
& vbCrLf
If Not
IsDBNull(row("AccountCode")) Then
sExportToExcel &= "<td>" & row("AccountCode").ToString & "</td>" & vbCrLf
Else
sExportToExcel &= "<td></td>" & vbCrLf
End If
If
Not IsDBNull(row("AccName"))
Then
sExportToExcel &= "<td>" & row("AccName").ToString & "</td>" & vbCrLf
Else
sExportToExcel &= "<td></td>" & vbCrLf
End If
If Not
IsDBNull(row("AccPhone")) Then
sExportToExcel &= "<td>" & row("AccPhone").ToString & "</td>" & vbCrLf
Else
sExportToExcel &= "<td></td>" & vbCrLf
End
If
If Not
IsDBNull(row("AccFAX")) Then
sExportToExcel &= "<td>" & row("AccFAX").ToString & "</td>" & vbCrLf
Else
sExportToExcel &= "<td></td>" & vbCrLf
End If
If Not
IsDBNull(row("AccEmail")) Then
sExportToExcel &= "<td>" & row("AccEmail").ToString & "</td>" & vbCrLf
Else
sExportToExcel &= "<td></td>" & vbCrLf
End If
If Not
IsDBNull(row("AccWebsite")) Then
sExportToExcel &= "<td>" & row("AccWebsite").ToString & "</td>" & vbCrLf
Else
sExportToExcel &= "<td></td>" & vbCrLf
End If
If Not
IsDBNull(row("AccDesc")) Then
sExportToExcel &= "<td>" & row("AccDesc").ToString & "</td>" & vbCrLf
Else
sExportToExcel &= "<td></td>" & vbCrLf
End If
If Not
IsDBNull(row("CreatedDate")) Then
sExportToExcel &= "<td>" & row("CreatedDate").ToString & "</td>" & vbCrLf
Else
sExportToExcel &= "<td></td>" & vbCrLf
End If
If Not
IsDBNull(row("ModifiedDate")) Then
sExportToExcel &= "<td>" & row("ModifiedDate").ToString & "</td>" & vbCrLf
Else
sExportToExcel &= "<td></td>" & vbCrLf
End If
sExportToExcel &= "</tr>"
& vbCrLf
End If
Next
sExportToExcel &= "</table></div>"
& vbCrLf
Return sExportToExcel
End Function
Private Sub
ExportToExcel(ByVal FileName As String)
Dim objBind As New DataTable
Dim sb As New System.Text.StringBuilder
Dim sExportToExcel As
String = ""
Dim style As String = "<style>.text{mso-number-format:\@;}</style>"
objBind = BindData()
If objBind.Rows.Count > 0 Then
sExportToExcel = ExportAccountToExcel(objBind)
sb.Append(sExportToExcel)
lblExport.Text = sb.ToString()
sb.Remove(0, sb.Length)
Response.Clear()
Response.Charset = ""
Response.ContentEncoding = System.Text.Encoding.UTF8
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/ms-excel.xls"
Response.AddHeader("content-disposition",
"attachment;filename=" &
FileName & ".xls")
Response.ContentEncoding = Encoding.Unicode
Response.BinaryWrite(Encoding.Unicode.GetPreamble())
Dim sw As
New System.IO.StringWriter
Dim htw As
New HtmlTextWriter(sw)
lblExport.RenderControl(htw)
Response.Output.Write(style & sw.ToString().Replace("td", "td
class='text'"))
Response.Flush()
Response.End()
End If
End Sub
#End Region
#Region "Bind Data"
Private Sub
BindAccount()
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 Function
BindData() 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 Sub
grvObject_RowCommand(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewCommandEventArgs)
Handles grvObject.RowCommand
Dim ItemID As Integer = Integer.Parse(e.CommandArgument)
Select Case
e.CommandName.ToLower
Case "view"
With CType(ucViewRecord,
ExportDatatableToExcel.UserControls.Popup_ViewRecord)
.ItemID = ItemID
.ShowPopup(ItemID)
End With
End Select
End Sub
Private Sub
grvObject_RowDeleting(ByVal sender As Object, ByVal e As System.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,
ExportDatatableToExcel.UserControls.Popup_ConfirmDelete)
.ItemID = ItemID
.ShowPopup(ItemID, "")
End With
End If
End Sub
Private Sub
grvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles
grvObject.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow)
Then
'Delete
Dim cmdDelete As
ImageButton = DirectCast(e.Row.FindControl("cmdDelete"), ImageButton)
If Not
cmdDelete Is Nothing
Then
cmdDelete.ToolTip = "Delete
Account"
End If
End If
End Sub
Private Sub
grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewPageEventArgs)
Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindAccount()
End Sub
#End Region
#Region "Popup"
Private Sub
MySelDelete_OnSelectedRow(ByVal sender As Object, ByVal e As
ExportDatatableToExcel.MyEventArgs)
Dim ItemName As String = ""
With e
If e.Id <> "" Then
BindAccount()
End If
End With
End Sub
#End Region
#Region "Event
Handles"
Protected Sub
Page_Load(ByVal sender As
Object, ByVal e
As System.EventArgs)
Handles Me.Load
Try
AddHandler CType(ucDeleteItem,
ExportDatatableToExcel.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 Sub
cmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdQuickSearch.Click
BindAccount()
End Sub
Private Sub
cmdExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdExport.Click
ExportToExcel("List-Account.xls")
End Sub
#End Region
End Class
End Namespace
Chúc các bạn thành công!
Quang Bình
No Comment to " Export danh sách dữ liệu (Datatable) ra Excel trong Asp.net "