(Đưa dữ liệu từ file Excel vào SQL Server trong Asp.net) – Thông thường trong phần mềm, để đưa dữ liệu vào bảng có 2 cách: nhập trực tiếp hoặc Import từ file. Với cách Import dữ liệu từ file sẽ giúp người nhập liệu tiết kiệm được rất nhiều thời gian cho việc nhập liệu mà lại tránh nhiều sai sót. 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 Import toàn bộ danh sách dữ liệu trong file Excel vào SQL Server.
- B1: Tạo CSDL SQL Customers
- B2: Tạo Bảng Players 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 | ItemID | Int | Trường tự tăng |
2 | Name | nvarchar(35) | |
3 | Midfield | nvarchar(50) | |
4 | Dateofbirth | Datetime | |
5 | Country | nvarchar(50) | |
6 | Club | nvarchar(50) | |
7 | Height | nvarchar(50) | |
8 | Weight | nvarchar(50) | |
9 | ImageURL | nvarchar(200) |
- B3: Nhập dữ liệu cho bảng Players
- B4: Tạo stored procedure trong SQL Server
USE[Customers]
GO
CREATE PROCEDURE [dbo].[Pro_Players_Add]
@Name nvarchar(40)
,@Midfield nvarchar(30)
,@Dateofbirth datetime
,@Country nvarchar(60)
,@Club nvarchar(15)
,@Height nvarchar(15)
,@Weight nvarchar(10)
,@ImageURL nvarchar(200)
AS
INSERT INTO Players (
[Name]
,[Midfield]
,[Dateofbirth]
,[Country]
,[Club]
,[Height]
,[Weight]
,[ImageURL]
) VALUES (
@Name
,@Midfield
,@Dateofbirth
,@Country
,@Club
,@Height
,@Weight
,@ImageURL
)
select SCOPE_IDENTITY()
Go
CREATE PROCEDURE [dbo].[Pro_Players_List]
@Keyword nvarchar(250)
AS
declare@strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'Select * from Players'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (Name like N''%'+@Keyword+'%''
Or Midfield like N''%' +@Keyword+'%'' Or Country like N''%' +@Keyword+'%''
Or Club like N''%' +@Keyword+'%'')'
set @strOrder =' Order by Name'
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql@strSQL- B4: 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 ImportDataFromExcelToSQL
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 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
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B5: Tạo file Import. aspx, mở và nhập mã HTML
<%@ PageTitle="Import Data from excel to SQL server in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Import.aspx.vb" Inherits="ImportDataFromExcelToSQL.Import" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table cellpadding="3"cellspacing="5"border="0"width="50%">
<tr>
<td>
<divclass="panel panel-default">
<divclass="panel-heading">
<asp:label id="lblHeader" runat="server" Text="IMPORT DATA"></asp:label>
</div>
<divclass="panel-body">
<table cellspacing="2"cellpadding="3"border="0"width="100%">
<tr>
<td style="width:8%;">
<asp:Label ID="plFileName"runat="server">File</asp:Label>
</td>
<td>
<asp:FileUpload ID="ImportFile"runat="server"CssClass="TextBox"/><br />
<asp:RequiredFieldValidatorID="rfvFileupload"ValidationGroup="validate"CssClass="NormalRed"runat="server"ErrorMessage="Select File Excel" ControlToValidate="ImportFile"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:label id="lblMessage"runat="server"></asp:label><br />
</td>
</tr>
</table>
</div>
<divclass="modal-footer">
<div class="btn-group">
<asp:LinkButton id="cmdImport"runat="server"CssClass="btn btn-small" ValidationGroup="validate" Causesvalidation="true">
<i class="icon-importexcel"></i> <asp:label id="lblImport" runat="server" Text="Import Excel"></asp:label>
</asp:LinkButton>
<asp:LinkButton id="cmdCancel"runat="server"CssClass="btn btn-small" Causesvalidation="false">
<i class="icon-back"></i> <asp:label id="lblBack" runat="server" Text="Back"></asp:label>
</asp:LinkButton>
</div>
</div>
</div>
</td>
</tr>
</table>
</asp:Content>
- B6: Viết Code cho file Import.aspx
'Visit http://thuthuatlaptrinh.blogspot.com for more ASP.NET Tutorials
Imports System.IO
Imports System.Data.OleDb
Namespace ImportDataFromExcelToSQL
Public Class Import
Inherits System.Web.UI.Page
#Region "Private Method"
Private SubCreateFolder()
Dim FilePath As String = MapPath("~/Import")
If Not Directory.Exists(FilePath) Then
' if not, create it.
Directory.CreateDirectory(FilePath)
End If
End Sub
Protected FunctionUploadFile(ByVal file AsFileUpload) AsString
Dim fileName As String
Dim filePath As String
fileName = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1)
filePath = MapPath("~/Import/"+ fileName)
file.SaveAs(filePath)
Return fileName
End Function
Protected FunctionExcelConnection(ByVal FileName As String) As OleDbCommand
Dim xConnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;"& _
"Data Source=" & Server.MapPath("~/Import/" & FileName) & ";" & _
"Extended Properties=Excel 8.0;"
Dim objXConn As New OleDbConnection(xConnStr)
objXConn.Open()
Dim objCommand As New OleDbCommand("SELECT * FROM [Player$]", objXConn)
Return objCommand
End Function
Protected FunctionReaderValue(ByVal MyReader As OleDbDataReader, ByVal iValue AsInteger) As String
Dim val As Object = Convert.ToString(MyReader(iValue))
If Not IsDBNull(val) Then
Return val.ToString()
Else
Return Convert.ToString(0)
End If
End Function
Private SubUpdateRecord(ByVal PlayerName As String, ByVal Midfield As String, ByValDateofbirth As Date, ByVal Country AsString, _
ByVal Club As String, ByVal Height As String, ByVal Weight As String, ByValImageURL As String)
Dim objSQL As New SqlDataProvider
objSQL.RunSQL("Pro_Players_Add", New ObjectPara("@Name", PlayerName), _
New ObjectPara("@Midfield", Midfield), _
New ObjectPara("@Dateofbirth", Dateofbirth), _
New ObjectPara("@Country", Country), _
New ObjectPara("@Club", Club), _
New ObjectPara("@Height", Height), _
New ObjectPara("@Weight", Weight), _
New ObjectPara("@ImageURL", ImageURL))
End Sub
#End Region
#Region "Event Handles"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
If NotIsPostBack Then
CreateFolder()
End If
Catch ex As Exception
End Try
End Sub
Private SubcmdImport_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdImport.Click
Try
Dim sFileName AsString = ""
Dim PlayerName AsString = ""
Dim Midfield AsString = ""
Dim Dateofbirth AsDate
Dim Country AsString = ""
Dim Club AsString = ""
Dim Height AsString = ""
Dim Weight AsString = ""
Dim ImageURL AsString = ""
If ImportFile.PostedFile.FileName <> "" Then
sFileName = UploadFile(ImportFile)
Dim objCommand AsNew OleDbCommand()
objCommand = ExcelConnection(sFileName)
' create a DataReader
Dim reader AsOleDbDataReader
reader = objCommand.ExecuteReader()
While reader.Read()
PlayerName = ReaderValue(reader, 0)
Midfield = ReaderValue(reader, 1)
Dateofbirth = ReaderValue(reader, 2)
Country = ReaderValue(reader, 3)
Club = ReaderValue(reader, 4)
Height = ReaderValue(reader, 5)
Weight = ReaderValue(reader, 6)
ImageURL = ReaderValue(reader, 7)
If PlayerName <> ""Then
UpdateRecord(PlayerName, Midfield, Dateofbirth, Country, Club, Height, Weight, ImageURL)
End If
End While
End If
Catch ex As Exception
lblMessage.Text = ex.Message
lblMessage.ForeColor = System.Drawing.Color.Red
Finally
lblMessage.Text = "Data Inserted Sucessfully"
lblMessage.ForeColor = System.Drawing.Color.Green
End Try
End Sub
Private Sub cmdCancel_Click(ByValsender As Object, ByVal e AsSystem.EventArgs) HandlescmdCancel.Click
Response.Redirect("Default.aspx")
End Sub
#End Region
End Class
End Namespace- B7: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ PageTitle="Import Data from excel to SQL server in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ImportDataFromExcelToSQL._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<h3>
Import Data from excel to SQL server in ASP.Net
</h3>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%">
<tr>
<td>
<asp:LinkButton id="cmdImport" runat="server" CssClass="btn btn-small" Causesvalidation="false">
<i class="icon-importexcel"></i> <asp:label id="lblImport" runat="server" Text="Import 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="12"
CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
BorderWidth="1"AutoGenerateColumns="false"DataKeyNames="PlayerID"width="100%">
<AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"/>
<RowStyle CssClass="GridStyle_RowStyle"/>
<pagerstyle cssclass="GridStyle_pagination"/>
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemStyle HorizontalAlign="Left"width="15%"/>
<ItemTemplate>
<asp:Label ID="lblName"Text='<%# Eval("Name") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Midfield">
<ItemStyle HorizontalAlign="Left"width="12%"/>
<ItemTemplate>
<asp:Label ID="lblMidfield"Text='<%# Eval("Midfield") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dateofbirth">
<ItemStyle HorizontalAlign="Center"width="10%"/>
<ItemTemplate>
<asp:Label ID="lblDateofbirth"Text='<%# Eval("Dateofbirth").ToShortDateString %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblCountry"Text='<%# Eval("Country") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Club">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblClub"Text='<%# Eval("Club") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Height">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblHeight"Text='<%# Eval("Height") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblWeight"Text='<%# Eval("Weight") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemStyle HorizontalAlign="Center"width="3%"/>
<ItemTemplate>
<asp:Image ID="imgPlayer"Width="40"ImageUrl='<%#Eval("ImageURL")%>' AlternateText='<%# Eval("ImageURL") %>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
- B8: Viết Code cho file Default.aspx
'Visit http://thuthuatlaptrinh.blogspot.com for more ASP.NET Tutorials
Namespace ImportDataFromExcelToSQL
Public Class _Default
Inherits System.Web.UI.Page
#Region "Bind Data"
Private SubBindPlayers()
Dim objBind As New DataTable
objBind = BindData(txtSearch.Text)
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
End If
updatePanel.Update()
End Sub
Private FunctionBindData(ByVal Keyword AsString) As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Players_List", New ObjectPara("@Keyword", Keyword.Trim))
Return objBind
End Function
#End Region
#Region "GridView Methods"
Private SubgrvObject_PageIndexChanging(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindPlayers()
End Sub
#End Region
#Region "Event Handles"
Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
Try
If Page.IsPostBack = False Then
'Default Submit Button
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
BindPlayers()
End If
Catch ex As Exception
End Try
End Sub
Private SubcmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdQuickSearch.Click
BindPlayers()
End Sub
Private SubcmdImport_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdImport.Click
Response.Redirect("Import.aspx")
End Sub
#End Region
End Class
End Namespace
- B9: Download file Excel mẫu tại đây
- B10: Chạy Project, kích nút Import -> chọn File Excel vừa download -> Kích nút Import, toàn bộ dữ liệu trong file Excel đã được đưa vào bảng Players trong SQL Server.
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment