Hướng dẫn Import dữ liệu và Database

10 3.5K 26
Hướng dẫn Import dữ liệu và Database

Đang tải... (xem toàn văn)

Thông tin tài liệu

Hướng dẫn Import dữ liệu và Database

 Hướng dẫn Import dữ liệu vào database từ tập tin excel trong C# Ở bài viết này, Góc Kinh Nghiệm 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 Góc Kinh Nghiệm sử dụng:• Microsoft Excel 2003• SQL Server 2005• 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 excelGiờ 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 định dạnh như hình bên dưới:Hình 2: thông tin đị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 table có tên EmployeeInfo như hình bên dưới: Hình 3: Database để lưu thông tin importLư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, 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:o TextBox: tên txtFilePath, dùng để chứa đường dẫn tập tin excel cần importo Button: tên btnBrowse, cho phép người dùng chọn tập tin excel cần importo 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 DataGridViewo DataGridView: tên dgvData, để chứa dữ liệu được lấy từ database sau khi import xongo 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), chọn database tên “HumanResourceDB” (database này đã tạo sẵn ở bước 2) -> nhấn nút OK -> nhất Next, 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 databaseCác chủ đề tương tự mới nhất:• Tất Cả Bài Tập Lập Trình Căn Bản, Đồ Họa, . • Visual Studio 2010 Ultimate Actived . Trả lời Trả Lời Với Trích Dẫn Thanks  15-09-2011 11:34 AM #2 hctru68 admin_tailieusv Tham gia ngàyJul 2011Nơi Cư NgụNinh Kiều, Cần ThơBài gởi216Thanks10Thanked 45 Times in 29 PostsSau 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ạoTrong đó:Nội dung các hàm lần lược như sau:GetData()SELECT [Index], Code, FullName, WorkingYearsFROM EmployeeInfoGetEmployeeInfoByCode()SELECT [Index], Code, FullName, WorkingYearsFROM EmployeeInfo Where Code = @CodeInsertEmployee()INSERT INTO [EmployeeInfo] ([Code], [FullName], [WorkingYears]) VALUES (@Code, @FullName, @WorkingYears);SELECT SCOPE_IDENTITY()UpdateEmployeeInfoByCode()UPDATE EmployeeInfoSET FullName = @FullName, WorkingYears = @WorkingYearsWHERE (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 importOpenFileDialog ofd = new OpenFileDialog();// Lấy đường dẫn file import vừa chọntxtFilePath.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ề DataTableDataTable data = ReadDataFromExcelFile();// Import dữ liệu đọc được vào databaseImportIntoDatabase(data);// Lấy hết dữ liệu import từ database hiển thị lên gridViewShowData();} 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";// Tạo đối tượng kết nốiOleDbConnection oledbConn = new OleDbConnection(connectionString);DataTable data = null;try{// Mở kết nốioledbConn.Open();// Tạo đối tượng OleDBCommand 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 excelOleDbDataAdapter oleda = new OleDbDataAdapter();oleda.SelectCommand = cmd;// Tạo đối tượng DataSet để hứng dữ liệu từ tập tin excelDataSet ds = new DataSet(); // Đổ đữ liệu từ tập excel vào DataSetoleda.Fill(ds);data = ds.Tables[0];}catch (Exception ex){MessageBox.Show(ex.ToString());}finally{// Đóng chuỗi kết nốioledbConn.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.EmployeeInfoTableAdapte r adapter = new HumanResourceTableAdapters.EmployeeInfoTableAdapte r();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ớiif (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ì updateelse{adapter.UpdateEmployeeInfoByCode(fullName, workingYears, code);}}}catch (Exception ex){MessageBox.Show(ex.ToString());}MessageBox.Show("Kết thúc import");}private void ShowData(){HumanResourceTableAdapters.EmployeeInfoTableAdapte r adapter = new HumanResourceTableAdapters.EmployeeInfoTableAdapte r();dgvData.DataSource = adapter.GetData();}}}Bước 8: Build chạy chương trình, thu được kết quả như hình 1 bên trênGóc Kinh Nghiệm chúc các bạn thành công! [...]... nối oledbConn.Open(); // Tạo đối tượng OleDBCommand 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 =...private bool ValidInput() { if (txtFilePath.Text.Trim() == "") { MessageBox.Show("Xin vui lòng chọn tập tin excel cần import& quot;); return false; } return true; } private DataTable ReadDataFromExcelFile() { string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtFilePath.Text.Trim() . Hướng dẫn Import dữ liệu vào database từ tập tin excel trong C# Ở bài viết này, Góc Kinh Nghiệm hướng dẫn bạn cách đọc dữ liệu tập tin excel, sau đó import. 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

Ngày đăng: 18/08/2012, 11:53

Hình ảnh liên quan

Hình 1: Giao diện form - Hướng dẫn Import dữ liệu và Database

Hình 1.

Giao diện form Xem tại trang 1 của tài liệu.
Hình 2: thông tin và định dạng tập tin excel - Hướng dẫn Import dữ liệu và Database

Hình 2.

thông tin và định dạng tập tin excel Xem tại trang 1 của tài liệu.
Hình - Hướng dẫn Import dữ liệu và Database

nh.

Xem tại trang 2 của tài liệu.
Hình 4: Tạo DataSet tên HummanResource.xsd - Hướng dẫn Import dữ liệu và Database

Hình 4.

Tạo DataSet tên HummanResource.xsd Xem tại trang 3 của tài liệu.
Hình 5: tạo - Hướng dẫn Import dữ liệu và Database

Hình 5.

tạo Xem tại trang 4 của tài liệu.
Sau khi hoàn tất Wizard, chúng ta được DataSet với kết quả hình như sau: - Hướng dẫn Import dữ liệu và Database

au.

khi hoàn tất Wizard, chúng ta được DataSet với kết quả hình như sau: Xem tại trang 5 của tài liệu.

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan