Mục tiêu:
Hiểu cách tích hợp ASP.NET Core MVC với tệp Excel.
Đọc dữ liệu từ tệp Excel và hiển thị trên giao diện web.
Tạo controller, model và view để hiển thị dữ liệu.
Yêu cầu:
IDE Visual Studio hoặc Visual Studio Code với .NET SDK 8.x/10.x
Cài đặt thư viện EPPlus để làm việc với tệp Excel.
Tệp dữ liệu Excel (ví dụ: products.xlsx) để lưu thông tin sản phẩm.
Tạo dự án ASP.NET Core MVC:
Mở Visual Studio hoặc Visual Studio Code.
Tạo một dự án ASP.NET Core Web Application với tên ExcelApp.
Chọn mẫu ASP.NET Core Web App (Model-View-Controller).
Cài đặt Thư viện EPPlus:
Mở Package Manager Console và chạy lệnh sau để cài đặt EPPlus:
Install-Package EPPlus
EPPlus là thư viện mạnh mẽ và miễn phí để thao tác với tệp Excel
Tạo tập tin Excel Mẫu:
Tạo tập tin Excel với tên products.xlsx trong thư mục Data (nếu thư mục này chưa có, hãy tạo mới).
Trong tập tin Excel, tạo bảng với các cột sau:
Id: Mã sản phẩm
Name: Tên sản phẩm
Price: Giá sản phẩm
Category: Loại sản phẩm
ReleaseDate: Ngày phát hành
Thêm dữ liệu mẫu vào bảng và lưu dưới tên products.xlsx trong thư mục Data
Thêm Model Product vào dự án với nội dung sau:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public DateTime ReleaseDate { get; set; }
}
Tạo Lớp ExcelDataAccess để Đọc Dữ liệu từ tập tin Excel:
Trong thư mục Data, tạo lớp ExcelDataAccess.cs để đọc dữ liệu từ tệp Excel.
Sử dụng EPPlus để đọc các hàng dữ liệu từ tệp Excel và chuyển đổi thành danh sách Product.
using ExcelApp.Models;
using OfficeOpenXml;
namespace ExcelApp.Data
{
public class ExcelDataAccess
{
private readonly string _filePath = Path.Combine(Directory.GetCurrentDirectory(), "Data", "products.xlsx");
public List<Product> GetAllProducts()
{
var products = new List<Product>();
ExcelPackage.License.SetNonCommercialPersonal("My Name");
using (var package = new ExcelPackage(new FileInfo(_filePath)))
{
ExcelWorksheet worksheet =
package.Workbook.Worksheets[0];
int rowCount = worksheet.Dimension.Rows;
for (int row = 2; row <= rowCount; row++)
{
var product = new Product
{
Id = int.Parse(worksheet.Cells[row, 1].Value.ToString()),
Name = worksheet.Cells[row, 2].Value.ToString(),
Price = decimal.Parse(worksheet.Cells[row, 3].Value.ToString()),
Category = worksheet.Cells[row, 4].Value.ToString(),
ReleaseDate = DateTime.Parse(worksheet.Cells[row, 5].Value.ToString())
};
products.Add(product);
}
}
return products;
}
}
}
Tạo Controller ProductsController:
Tạo một controller mới có tên ProductsController trong thư mục Controllers
using ExcelApp.Data;
using Microsoft.AspNetCore.Mvc;
namespace ExcelApp.Controllers
{
public class ProductsController : Controller
{
private readonly ExcelDataAccess _excelDataAccess = new ExcelDataAccess();
public IActionResult Index()
{
var products = _excelDataAccess.GetAllProducts();
return View(products);
}
public IActionResult Details(int id)
{
var products = _excelDataAccess.GetAllProducts();
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
return View(product);
}
}
}
Tạo View cho Index (Danh sách Sản phẩm):
Tạo một View mới có tên Index.cshtml trong thư mục Views/Products để hiển thị danh sách sản phẩm:
@model IEnumerable<ExcelApp.Models.Product>
<h2>Danh sách Sản phẩm</h2>
<table class="table">
<tr>
<th>ID</th>
<th>Tên Sản phẩm</th>
<th>Giá</th>
<th>Danh mục</th>
<th>Ngày phát hành</th>
<th>Hành động</th>
</tr>
@foreach (var product in Model)
{
<tr>
<td>@product.Id</td>
<td>@product.Name</td>
<td>@product.Price</td>
<td>@product.Category</td>
<td>@product.ReleaseDate.ToShortDateString()</td>
<td>
<a asp-action="Details" asp-route-
id="@product.Id">Chi tiết</a>
</td>
</tr>
}
</table>
Tạo View cho Details (Chi tiết Sản phẩm):
Tạo một View mới có tên Details.cshtml trong thư mục Views/Products để hiển thị chi tiết sản phẩm:
@model ExcelApp.Models.Product
<h2>Chi tiết Sản phẩm</h2>
<dl class="row">
<dt class="col-sm-2">ID</dt>
<dd class="col-sm-10">@Model.Id</dd>
<dt class="col-sm-2">Tên</dt>
<dd class="col-sm-10">@Model.Name</dd>
<dt class="col-sm-2">Giá</dt>
<dd class="col-sm-10">@Model.Price</dd>
<dt class="col-sm-2">Danh mục</dt>
<dd class="col-sm-10">@Model.Category</dd>
<dt class="col-sm-2">Ngày phát hành</dt>
<dd class="col-sm-10">@Model.ReleaseDate.ToShortDateString()</dd>
</dl>
<a asp-action="Index">Quay lại danh sách</a>
1. Chạy ứng dụng
Nhấn Ctrl + F5 để chạy ứng dụng.
Truy cập vào đường dẫn https://localhost:{PORT}/Products để xem danh sách sản phẩm được đọc từ tệp products.xlsx.
2. Kiểm tra các chức năng:
Xem danh sách sản phẩm: Kiểm tra xem danh sách sản phẩm có được hiển thị chính xác không.
Xem chi tiết sản phẩm: Bấm vào liên kết "Chi tiết" để xem thông tin chi tiết của từng sản phẩm.