Đọc dữ liệu trong file Excel bằng thư viện Microsoft Office Object Library

Ở bài trước Tui có hướng dẫn cách thức xuất dữ liệu ra File Excel để báo cáo. Các bạn đã làm thành công, tuy nhiên một số bạn có Email nhờ hướng dẫn cách đọc dữ liệu trong file Excel rồi hiển thị lên WPF như thế nào. Nhân tiện có bài hướng dẫn Sinh viên trong Khoa thực hiện bài này nên Tui sẽ viết lại chi tiết cách lập trình:

Hình trên minh họa có 1 file Excel danh sách nhân viên có các cột: Mã, Tên, Tuổi. Giao diện WPF nhấn vào “Đọc Excel” thì dữ liệu từ Excel sẽ được hiển thị lên giao diện WPF.

Dữ liệu file Excel ở đây: https://duythanhcse.files.wordpress.com/2019/10/danhsachnhanvien.xlsx

Bây giờ tiến hành coding WPF, tạo đại một project bằng WPF. Ví dụ tên “K18411_N1_QuanLyNhanVien” (do Tui đang help Sinh Viên làm và note lại).

Sau đó Ta bấm chuột phải vào Reference/ chọn Add Reference:

Lúc này màn hình Reference Manager hiển thị lên như dưới đây:

Trong màn hình trên ta vào mục Com: rồi tick chọn 2 thư viện:

  • Microsoft Excel 16.0 Object Library (tùy version của bạn)
  • Microsoft Office 16.0 Object Library (tùy version của bạn)

Sau đó nhấn OK, nhìn trong Reference của dự án sẽ thấy 2 thư viện này:

Tiếp tục tạo 2 thư mục Models và IOs cho project (bấm chuột phải vào dự án rồi chọn new folder):

Trong Models tạo lớp Nhân Viên như dưới đây (bấm chuột phải vào Models/chọn Add Class):

[code language=”csharp”]

namespace K18411_N1_QuanLyNhanVien.Models

{

[Serializable]

public class NhanVien

{

public string Ma { get; set; }

public string Ten { get; set; }

public int Tuoi { get; set; }

}

}

[/code]

Trong IOs tạo một lớp tên ExcelFactory, nhiệm vụ của nó là đọc Excel và trả về danh sách Nhân viên:

Vào lớp ExcelFactory coding như sau:

[code language=”csharp”]

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Microsoft.Office.Interop.Excel;

using K18411_N1_QuanLyNhanVien.Models;

namespace K18411_N1_QuanLyNhanVien.IOs

{

public class ExcelFactory

{

public static List<NhanVien> readFromExcelFile(string path)

{

List<NhanVien> dsNV = new List<NhanVien>();

try

{

Workbook MyBook = null;

Application MyApp = null;

Worksheet MySheet = null;

MyApp = new Application();

MyApp.Visible = false;

MyBook = MyApp.Workbooks.Open(path);

MySheet = (Worksheet)MyBook.Sheets[1];

int lastRow = MySheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell).Row;

int lastColumn = MySheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell).Column;

int step = 2;

for (int i = step; i <= lastRow; i++)

{

Range rowContent_cellLeft = MySheet.Cells[i, 1];

Range rowContent_cellRight = MySheet.Cells[i, 3];

System.Array rowContent = (System.Array)MySheet.get_Range(rowContent_cellLeft, rowContent_cellRight).Cells.Value;

if (rowContent.GetValue(1, 1) == null)

break;

string ma = rowContent.GetValue(1, 1) + "";

string ten = rowContent.GetValue(1, 2) + "";

int tuoi = int.Parse( rowContent.GetValue(1, 3) + "");

NhanVien nv = new NhanVien();

nv.Ma = ma;

nv.Ten = ten;

nv.Tuoi = tuoi;

dsNV.Add(nv);

}

MyBook.Close(true);

MyApp.Quit();

releaseObject(MySheet);

releaseObject(MyBook);

releaseObject(MyApp);

}

catch (Exception ex)

{

throw ex;

}

return dsNV;

}

private static void releaseObject(object obj)

{

try

{

System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);

obj = null;

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

obj = null;

}

finally

{ GC.Collect(); }

}

}

}

[/code]

Bây giờ tạo một Window mới tên là “frmQuanLyNhanVien” (bạn có thể dùng chính màn hình MainWindow để thiết kế cũng được),

Tui tạo màn hình mới: nhấn chuột phải vào dự án chọn Add/ chọn Window rồi đặt tên cửa sổ là frmQuanLyNhanVien:

XAML code:

[code language=”xml”]

<Window x:Class="K18411_N1_QuanLyNhanVien.frmDanhSachNhanVien"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:K18411_N1_QuanLyNhanVien"
mc:Ignorable="d"
Title="frmDanhSachNhanVien" Height="450" Width="800">
<Grid>
<DataGrid x:Name="dgNhanVien" HorizontalAlignment="Left" Height="276" Margin="10,49,0,0" VerticalAlignment="Top" Width="776"/>
<Button x:Name="btnDocExcel" Content="Đọc Excel" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Click="BtnDocExcel_Click"/>

</Grid>
</Window>

[/code]

Coding để gọi thư viện đọc Excel:

[code language=”csharp”]

using System.Collections.Generic;

using System.Windows;

using Microsoft.Win32;

using K18411_N1_QuanLyNhanVien.Models;

using K18411_N1_QuanLyNhanVien.IOs;

namespace K18411_N1_QuanLyNhanVien

{

/// <summary>

/// Interaction logic for frmDanhSachNhanVien.xaml

/// </summary>

public partial class frmDanhSachNhanVien : Window

{

public frmDanhSachNhanVien()

{

InitializeComponent();

}

List<NhanVien> dsNV = null;

private void BtnDocExcel_Click(object sender, RoutedEventArgs e)

{

OpenFileDialog ofd = new OpenFileDialog();

if(ofd.ShowDialog()==true)

{

string file = ofd.FileName;

dsNV = ExcelFactory.readFromExcelFile(file);

dgNhanVien.ItemsSource = dsNV;

}

}

}

}

[/code]

Vào App.xaml chỉnh cho frmDanhSachNhanVien chạy trước – chỉnh StartupUri (Nếu lúc nãy bạn dùng MainWindow thì không cần chỉnh lại App.xaml):

[code language=”xml”]

<Application x:Class="K18411_N1_QuanLyNhanVien.App"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:local="clr-namespace:K18411_N1_QuanLyNhanVien"

StartupUri="frmDanhSachNhanVien.xaml">

<Application.Resources>

</Application.Resources>

</Application>

[/code]

Bây giờ F5 để chạy phần mềm lên, nhấn vào nút “Đọc Excel”, ta trỏ tới file danhsachnhanvien.xlsx :

Sau khi chọn file excel thì Nhấn nút “Open”, Kết quả đã như mong muốn:

Coding tải ở đây: https://www.mediafire.com/file/r5kt5vlgksnq1zv/K18411_N1_QuanLyNhanVien.zip/file

Chúc các bạn thành công

One thought on “Đọc dữ liệu trong file Excel bằng thư viện Microsoft Office Object Library”

Leave a Reply