Import dữ liệu từ Excel vào SQL Server trong Asp.net
(Đư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
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 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 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
#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
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
<%@ Page
Title="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>
<div
class="panel
panel-default">
<div
class="panel-heading">
<asp:label id="lblHeader" runat="server" Text="IMPORT DATA"></asp:label>
</div>
<div
class="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:RequiredFieldValidator
ID="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>
<div
class="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 Sub
CreateFolder()
Dim FilePath As String = MapPath("~/Import")
If Not Directory.Exists(FilePath)
Then
' if not, create it.
Directory.CreateDirectory(FilePath)
End If
End Sub
Protected Function
UploadFile(ByVal file As
FileUpload) As
String
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 Function
ExcelConnection(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 Function
ReaderValue(ByVal MyReader As OleDbDataReader,
ByVal iValue As
Integer) 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 Sub
UpdateRecord(ByVal PlayerName As String, ByVal Midfield As String, ByVal
Dateofbirth As Date,
ByVal Country As
String, _
ByVal Club As String, ByVal Height As String, ByVal Weight As String, ByVal
ImageURL 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 Not
IsPostBack Then
CreateFolder()
End If
Catch ex As Exception
End Try
End Sub
Private Sub
cmdImport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdImport.Click
Try
Dim sFileName As
String = ""
Dim PlayerName As
String = ""
Dim Midfield As
String = ""
Dim Dateofbirth As
Date
Dim Country As
String = ""
Dim Club As
String = ""
Dim Height As
String = ""
Dim Weight As
String = ""
Dim ImageURL As
String = ""
If ImportFile.PostedFile.FileName
<> "" Then
sFileName = UploadFile(ImportFile)
Dim objCommand As
New OleDbCommand()
objCommand = ExcelConnection(sFileName)
' create a DataReader
Dim reader As
OleDbDataReader
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(ByVal
sender As Object,
ByVal e As
System.EventArgs) Handles
cmdCancel.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
<%@ Page
Title="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>
<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="12"
CssClass="GridStyle"
BorderColor="#cbcbcb"
BorderStyle="solid"
BorderWidth="1"
AutoGenerateColumns="false"
DataKeyNames="PlayerID"
width="100%">
<AlternatingRowStyle
CssClass="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 Sub
BindPlayers()
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 Function
BindData(ByVal Keyword As
String) 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 Sub
grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewPageEventArgs)
Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindPlayers()
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 Page.IsPostBack = False Then
'Default Submit Button
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
BindPlayers()
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
BindPlayers()
End Sub
Private Sub
cmdImport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdImport.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
No Comment to " Import dữ liệu từ Excel vào SQL Server trong Asp.net "