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:https://i0.wp.com/gockinhnghiem.com/wp-content/uploads/FormImport.gif

Hình 1: Giao diện form import excel

Giờ chúng ta cùng Góc Kinh Nghiệm 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:https://i0.wp.com/gockinhnghiem.com/wp-content/uploads/Dinh-dang-tap-tin-import.gif

Hình 2: thông tin và định dạng tập tin excel cần import

  • Bước 2: Vào SQL Server 2005 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 2000 để thao tác (không nhất thiết là SQL Server 2005)

  • 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:https://i0.wp.com/gockinhnghiem.com/wp-content/uploads/Query.gif

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()

1
2
SELECT[Index], Code, FullName, WorkingYears
FROMEmployeeInfo

GetEmployeeInfoByCode()

1
2
3
SELECT[Index], Code, FullName, WorkingYears
FROMEmployeeInfo
WhereCode = @Code

InsertEmployee()

1
2
INSERTINTO[EmployeeInfo] ([Code], [FullName], [WorkingYears]) VALUES(@Code, @FullName, @WorkingYears);
SELECTSCOPE_IDENTITY()

UpdateEmployeeInfoByCode()

1
2
3
UPDATEEmployeeInfo
SETFullName = @FullName, WorkingYears = @WorkingYears
WHERE(Code = @Original_Code);
  • Bước 7: quay lại form FormMain, code như bên dưới:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Data.OleDb;
namespaceImportExcel
{
    publicpartialclassFormMain : Form
    {
        publicFormMain()
        {
            InitializeComponent();
            btnBrowse.Click += newEventHandler(btnBrowse_Click);
            btnImportExcel.Click += newEventHandler(btnImportExcel_Click);
        }
        voidbtnBrowse_Click(objectsender, EventArgs e)
        {
            // Browse đến file cần import
            OpenFileDialog ofd = newOpenFileDialog();
            // Lấy đường dẫn file import vừa chọn
            txtFilePath.Text = ofd.ShowDialog() == DialogResult.OK ? ofd.FileName : "";
        }
        voidbtnImportExcel_Click(objectsender, 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();
        }
        privateboolValidInput()
        {
            if(txtFilePath.Text.Trim() == "")
            {
                MessageBox.Show("Xin vui lòng chọn tập tin excel cần import");
                returnfalse;
            }
            returntrue;
        }
        privateDataTable ReadDataFromExcelFile()
        {
            stringconnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ txtFilePath.Text.Trim() + ";Extended Properties=Excel 8.0";
            // Tạo đối tượng kết nối
            OleDbConnection oledbConn = newOleDbConnection(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 = newOleDbCommand("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 = newOleDbDataAdapter();
                oleda.SelectCommand = cmd;
                // Tạo đối tượng DataSet để hứng dữ liệu từ tập tin excel
                DataSet ds = newDataSet();
                // Đổ đữ 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();
            }
            returndata;
        }
        privatevoidImportIntoDatabase(DataTable data)
        {
            if(data == null|| data.Rows.Count == 0)
            {
                MessageBox.Show("Không có dữ liệu để import");
                return;
            }
            HumanResourceTableAdapters.EmployeeInfoTableAdapter adapter = newHumanResourceTableAdapters.EmployeeInfoTableAdapter();
            stringcode = "", fullName = "";
            intworkingYears = 0;
            try
            {
                for(inti = 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");
        }
        privatevoidShowData()
        {
            HumanResourceTableAdapters.EmployeeInfoTableAdapter adapter = newHumanResourceTableAdapters.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

//

int i = 2; // Với i là Sheet cần load của file Excel đó.
string query = String.Format(“select * from [Sheet{0}$]”, i);// Ở đây lấy dữ liệu của Sheet2

Leave a comment