Hướng dẫn Import dữ liệu vào database từ tập tin excel
trong c#
Bài
viết này hướng dẫn bạn cách đọc dữ liệu tập tin excel, sau đó import dữ liệu
đọc được vào database.
Ở đây chúng ta sử
dụng:
- MS Excel 2003 hoặc MS Excel 2007 hoặc MS Excel 2013
- SQL Server 2008
- Visual Studio 2010 (Win Form)
Mô tả:
Người dùng nhất vào
nút “Browse …” để chọn tập tin excel cần import. Kế tiếp nhấn nút “Import
excel” để thực thiện việc import dữ liệu vào database. Sau khi kết thúc import
xong, lấy tất cả dữ liệu từ dabase hiển thị lên DataGridView, kết quả như hình
bên dưới:

Hình 1: Giao diện form import excel
Giờ chúng ta cùng lần
lượt làm theo các bước sau:
- Bước 1: Tạo tập tin import tên
EmployeeInfo.xls có thông tin và định dạnh như hình bên dưới:
Hình 2: thông tin và định dạng tập tin excel cần import
- Bước 2: Vào SQL Server 2008 tạo
cơ sở dữ liệu có tên HumanResourceDB và table có tên EmployeeInfo như hình
bên dưới:
Hình 3: Database để lưu thông tin import
Lưu ý: ở đây bạn cũng
có thể dụng SQL Server 2005 để thao tác (không nhất thiết là SQL Server 2008)
- Bước 3: Mở Visual Studial 2010
(bạn cũng có thể dùng VS2005, VS2008 để thao tác), Vào File -> New
-> Project … -> Windows (phía bên trái) -> Windows Forms
Application, và gõ vào ô Name bên tên project là ImportExcel
- Bước 4: Sau khi project được
tạo, bạn đổi tên Form1 thành FormMain, vào design của FormMain tạo các đối
tượng sau:
§
TextBox: tên
txtFilePath, dùng để chứa đường dẫn tập tin excel cần import
§
Button: tên btnBrowse,
cho phép người dùng chọn tập tin excel cần import
§
Button: tên
btnImportExcel, thực hiện import khi người dùng nhấn vào nút này, sau khi
import thành công sẽ hiển thị dữ liệu lên DataGridView
§
DataGridView: tên
dgvData, để chứa dữ liệu được lấy từ database sau khi import xong
§
Lable “File Path” tùy
ý
Tham khảo hình 1 ở
trên
- Bước 5: Nhất chuột phải lên
project ImportExcel -> Add -> New Item .. -> Data (bên trái)
-> DataSet (bên phải), gõ tên HumanResource.xsd vào ô Name như hình bên
dưới
Hình 4: Tạo DataSet tên HummanResource.xsd
- Bước 6: Nhấn chuột phải vào vào
DataSet vừa tạo ở bước 5, chọn Add -> TableAdapter …, hiện ra một hộp
thoại TableAdapter Cofiguration Wizard -> nhấn nút New Connection …,
-> xuất hiện hộp thoại tên Add Connection, gõ dấu chấm (.) vào ô Server
Name (dấu chấm ở đây đại diện cho localhost, tức SQL Server đang được cài
trên máy hiện hành của bạn), và chọn database tên “HumanResourceDB”
(database này đã tạo sẵn ở bước 2) -> nhấn nút OK -> nhất Next, và
làm theo chỉ dẫn của wizard, xem hình bên dưới:
Hình 5: tạo kết nối với database
Sau khi hoàn tất
Wizard, chúng ta được DataSet với kết quả hình như sau:
Hình 6: kết quả của DataSet được tạo
Trong đó:
Nội dung các hàm
lần lược như sau:
GetData()
SELECT [Index], Code, FullName, WorkingYears FROM EmployeeInfo
GetEmployeeInfoByCode()
SELECT [Index], Code, FullName, WorkingYears FROM EmployeeInfo Where Code = @Code
InsertEmployee()
INSERT INTO [EmployeeInfo] ([Code], [FullName], [WorkingYears]) VALUES (@Code, @FullName, @WorkingYears); SELECT SCOPE_IDENTITY()
UpdateEmployeeInfoByCode()
UPDATE EmployeeInfo SET FullName = @FullName, WorkingYears = @WorkingYears WHERE (Code = @Original_Code);
- Bước 7: quay lại form FormMain,
code như bên dưới:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace ImportExcel
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
btnBrowse.Click += new EventHandler(btnBrowse_Click);
btnImportExcel.Click += new EventHandler(btnImportExcel_Click);
}
void btnBrowse_Click(object sender, EventArgs e)
{
// Browse đến file cần import
OpenFileDialog ofd = new OpenFileDialog();
// Lấy đường dẫn file import vừa chọn
txtFilePath.Text = ofd.ShowDialog() == DialogResult.OK ? ofd.FileName : "";
}
void btnImportExcel_Click(object sender, EventArgs e)
{
if (!ValidInput())
return;
// Đọc dữ liệu từ tập tin excel trả về DataTable
DataTable data = ReadDataFromExcelFile();
// Import dữ liệu đọc được vào database
ImportIntoDatabase(data);
// Lấy hết dữ liệu import từ database hiển thị lên gridView
ShowData();
}
private bool ValidInput()
{
if (txtFilePath.Text.Trim() == "")
{
MessageBox.Show("Xin vui lòng chọn tập tin excel cần import");
return false;
}
return true;
}
private DataTable ReadDataFromExcelFile()
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtFilePath.Text.Trim() + ";Extended Properties=Excel 8.0";
//Nếu là Excel 2003 -> Extended Properties=Excel 8.0
//Nếu là Excel 2007 -> Extended Properties=Excel 12.0
//Nếu là Excel 2013 -> Extended Properties=Excel 14.0
// Tạo đối tượng kết nối
OleDbConnection oledbConn = new OleDbConnection(connectionString);
DataTable data = null;
try
{
// Mở kết nối
oledbConn.Open();
// Tạo đối tượng OleDBCommand và query data từ sheet có tên "Sheet1"
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
// Tạo đối tượng OleDbDataAdapter để thực thi việc query lấy dữ liệu từ tập tin excel
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
// Tạo đối tượng DataSet để hứng dữ liệu từ tập tin excel
DataSet ds = new DataSet();
// Đổ đữ liệu từ tập excel vào DataSet
oleda.Fill(ds);
data = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
// Đóng chuỗi kết nối
oledbConn.Close();
}
return data;
}
private void ImportIntoDatabase(DataTable data)
{
if (data == null || data.Rows.Count == 0)
{
MessageBox.Show("Không có dữ liệu để import");
return;
}
HumanResourceTableAdapters.EmployeeInfoTableAdapter adapter = new HumanResourceTableAdapters.EmployeeInfoTableAdapter();
string code = "", fullName = "";
int workingYears = 0;
try
{
for (int i = 0; i < data.Rows.Count; i++)
{
code = data.Rows[i]["Code"].ToString().Trim();
fullName = data.Rows[i]["FullName"].ToString().Trim();
workingYears = int.Parse(data.Rows[i]["WorkingYears"].ToString().Trim());
HumanResource.EmployeeInfoDataTable existingEmployee = adapter.GetEmployeeInfoByCode(code);
// Nếu nhân viên chưa tồn tại trong DB thì thêm mới
if (existingEmployee == null || existingEmployee.Rows.Count == 0)
{
adapter.InsertEmployee(code, fullName, workingYears);
}
// Ngược lại, nhân viên đã tồn tại trong DB thì update
else
{
adapter.UpdateEmployeeInfoByCode(fullName, workingYears, code);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
MessageBox.Show("Kết thúc import");
}
private void ShowData()
{
HumanResourceTableAdapters.EmployeeInfoTableAdapter adapter = new HumanResourceTableAdapters.EmployeeInfoTableAdapter();
dgvData.DataSource = adapter.GetData();
}
}
}
Bước 8: Build và chạy chương trình, thu được kết quả như hình 1 bên trên.
Chúc các bạn thành công!
(theo gockinhnghiem.com)





Không có nhận xét nào:
Đăng nhận xét