Đọ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

Đa ngôn ngữ trong WPF – multilanguage in WPF

Topic này Tôi muốn hướng dẫn các bạn cách thiết lập đa ngôn ngữ cho một ứng dụng WPF

Vì đang bận một số việc nên Tôi chưa kịp viết Step by Step để giải thích từng dòng lệnh, nên tạm thời Tôi cung cấp link source code :

http://www.mediafire.com/?60lc924zu2w72p1

Link Demo ở trên sẽ tự động chọn đúng Language Location trong máy tính của bạn. Bạn có thể kiểm thử lại bằng cách vào Control Panel đổi qua Location khác.

Hiện tại Tôi Demo 3 ngôn ngữ: Tiếng Việt, Tiếng anh, Tiếng Pháp. Các bạn có thể lên mạng tìm các mã location của các quốc gia để tạo thêm các tập tin .xaml ngôn ngữ (mỗi ngôn ngữ sẽ nằm trong 1 tập tin .xaml, ở đây Tôi tạo 1 thư mục tên la Resources, bạn có thể đặt tên thư mục là gì cũng được ví dụ thay vì Resources bạn có thể đặt tên là LanguageTeo)

Các bạn chú ý các lệnh :

xmlns:y=”clr-namespace:System;assembly=mscorlib”

string s = Thread.CurrentThread.CurrentCulture.ToString();

Tôi nghĩ coding Tôi viết rất rõ ràng nên các bạn có thể tự suy luận ra, không cần comment.

Giao diện khi bạn chọn ngôn ngữ vào bấm change language sẽ như sau (Chương trình khi chạy lên nó sẽ tự động chọn đúng language location của máy bạn), Sau đó bạn thích chuyển qua ngôn ngữ nào thì tùy:

Hình ảnh minh họa như sau:

Khi bạn chọn tiếng Việt:

Khi chọn tiếng Pháp:

private void button2_Click(object sender, RoutedEventArgs e)

{

string s = “en-US”;

if (radtiengviet.IsChecked == true)

{

s=”vi-VN”;

}

else if (radtiengphap.IsChecked == true)

{

s=”fr-CA”;

}

else

{

s = “en-US”;

}

setLanguage(s);

}

public void setLanguage(string s)

{

ResourceDictionary dic = new ResourceDictionary();

this.Resources.MergedDictionaries.Clear();

this.Resources.MergedDictionaries.Add(dic);

switch (s)

{

case “vi-VN”:

dic.Source = new Uri(“../Resources/myresource.vi-VN.xaml”, UriKind.Relative);

break;

case “en-US”:

dic.Source = new Uri(“../Resources/myresource.xaml”, UriKind.Relative);

break;

case “fr-CA”:

dic.Source = new Uri(“../Resources/myresource.fr-CA.xaml”, UriKind.Relative);

break;

default:

dic.Source = new Uri(“../Resources/myresource.xaml”, UriKind.Relative);

break;

}

}

public void setLanguage()

{

string s = Thread.CurrentThread.CurrentCulture.ToString();

setLanguage(s);

}

private void Window_Loaded(object sender, RoutedEventArgs e)

{

setLanguage();

}

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