EPPlus là một thư viện .NET dùng để đọc và ghi các tập tin Excel. Để đọc file Excel bằng EPPlus trong MVC.NET C#, bạn có thể làm theo các bước sau:
- Cài đặt EPPlus: Để sử dụng EPPlus, bạn cần cài đặt thư viện EPPlus bằng cách thêm thư viện EPPlus vào project bằng cách sử dụng NuGet Package Manager trong Visual Studio.
- Tạo đối tượng ExcelPackage: Đầu tiên, bạn cần tạo một đối tượng ExcelPackage bằng cách truyền vào đường dẫn đến tập tin Excel cần đọc.
- Lấy Sheet từ tập tin Excel: Sau đó, bạn cần lấy Sheet từ tập tin Excel bằng cách truy cập thuộc tính Worksheets của đối tượng ExcelPackage.
- Đọc dữ liệu từ Sheet: Cuối cùng, bạn có thể đọc dữ liệu từ Sheet bằng cách sử dụng các phương thức của đối tượng ExcelWorksheet.
Lưu ý rằng bạn nên gọi phương thức Dispose() của đối tượng ExcelPackage khi bạn đã hoàn thành việc sử dụng nó để giải phóng tài nguyên và tránh lãng phí
Bài viết này hướng dẫn chúng ta cách đọc dữ liệu từ 1 tệp excel sử dụng Framework EPPlus.
File excel mẫu có dạng như sau:
Thực hiện:
Tao 1 Controller trong project có tên: DefaultController , trong controller này khai báo phương thức Get và khai báo đối tượng Sinh viên có cấu trúc như sau:
public class DefaultController : Controller
{
public List<SinhVien> ListAll = new List<SinhVien>();
// GET: Default
public ActionResult Index()
{
var model = ListAll;
return View(model);
}
}
// khai báo đối tượng chứa dữ liệu đọc được từ file excel
public class SinhVien
{
[Display(Name = "ID")]
public int SinhVien_ID { get; set; }
[Display(Name ="Mã sinh viên")]
public string SinhVien_Key { get; set; }
[Display(Name = "Họ, tên đệm")]
public string SinhVien_LastName { get; set; }
[Display(Name = "Tên")]
public string SinhVien_FistName { get; set; }
public SinhVien() { }
public SinhVien(int id, string key, string last_name, string fist_name)
{
this.SinhVien_ID = id;
this.SinhVien_Key = key;
this.SinhVien_LastName = last_name;
this.SinhVien_FistName = fist_name;
}
}
===================================================================================
Tạo view (index.cshtml) cho phương thức Get có mã nguồn như sau:
@model IEnumerable<ReadFileExcel.Controllers.SinhVien>
@{Layout = null;}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Default", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
File: @Html.TextBox("UploadedFile", "", new { type = "file", accept = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" })
<input type="submit" name="Submit" value="Đọc dữ liệu" />
}
<table rules="all" border="1">
<tr>
<th>@Html.DisplayNameFor(model => model.SinhVien_ID)</th>
<th>@Html.DisplayNameFor(model => model.SinhVien_Key)</th>
<th>@Html.DisplayNameFor(model => model.SinhVien_LastName)</th>
<th>@Html.DisplayNameFor(model => model.SinhVien_FistName)</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.SinhVien_ID)</td>
<td>@Html.DisplayFor(modelItem => item.SinhVien_Key)</td>
<td>@Html.DisplayFor(modelItem => item.SinhVien_LastName)</td>
<td>@Html.DisplayFor(modelItem => item.SinhVien_FistName)</td>
</td>
</tr>
}
</table>
</body>
</html>
Thực hiện cài đặt thư viện EPPlus (bản 4.5 free) vào project và viết thêm phương thức Post thực hiện việc đọc dữ liệu từ file excel có nội dung như sau:
public class DefaultController : Controller
{
// GET: Default
public List<SinhVien> ListAll = new List<SinhVien>();
public ActionResult Index()
{
var model = ListAll;
return View(model);
}
[HttpPost, ActionName("Index")]
public ActionResult ShowDataExcelFile()
{
ListAll = new List<SinhVien>();
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
using (var package = new ExcelPackage(file.InputStream))
{
var currentSheet = package.Workbook.Worksheets;
var workSheet = currentSheet.First();
var noOfCol = workSheet.Dimension.End.Column;
var noOfRow = workSheet.Dimension.End.Row;
int i = 1;
for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
var item = new SinhVien();
item.SinhVien_ID = i++;
item.SinhVien_Key = workSheet.Cells[rowIterator, 1].Value.ToString();
item.SinhVien_LastName = workSheet.Cells[rowIterator, 2].Value.ToString();
item.SinhVien_FistName = workSheet.Cells[rowIterator, 3].Value.ToString();
ListAll.Add(item);
}
}
/*ViewBag.show = "Có tổng số: " + ListAll.Count + " bản ghi";*/
}
else{ /*ViewBag.show = "Vui lòng chọn file";*/}
}
var model = ListAll;
return View(model.ToList());
}
}
// khai báo đối tượng chứa dữ liệu đọc được từ file excel
public class SinhVien
{
[Display(Name = "ID")]
public int SinhVien_ID { get; set; }
[Display(Name ="Mã sinh viên")]
public string SinhVien_Key { get; set; }
[Display(Name = "Họ, tên đệm")]
public string SinhVien_LastName { get; set; }
[Display(Name = "Tên")]
public string SinhVien_FistName { get; set; }
public SinhVien() { }
public SinhVien(int id, string key, string last_name, string fist_name)
{
this.SinhVien_ID = id;
this.SinhVien_Key = key;
this.SinhVien_LastName = last_name;
this.SinhVien_FistName = fist_name;
}
}
Cuối cùng, chạy thử chương trình và xem kết quả.
(Tham khảo mã nguồn đính kèm)