Read Data Excel using ASP.NET Core 2.1

Đọc dữ liệu từ file Excel, sử dụng trong ASP.NET Core 2.1, trong các trình quản lý dữ liệu, thường ta sử dụng import một file Excel để rút ngắn lại thời gian cho việc nhập liệu

Bước 1: Trong Visual Studio 2019, Bạn chọn File->New, chọn Project
Bước 2: Chọn Create a new project
Bước 3: Chọn ASP.NET Core Web Application template
Bước 4: Đặt tên Project, chọn Create. 
Bước 5: Select .NET Core, ASP.NET Core 2.1, Chọn Web Application (Model-View-Controller), sau đó bấm Create

Trong bài viết này ta sử dụng thư viện ExcelDataReader dùng để đọc dữ liệu file excel, nên ta cần mở Nuget Package Manager và cài đặt thư viện sau
+ ExcelDataReader
+ System.Text.Encoding.CodePages

Read Data Excel using ASP.NET Core 2.1

Read Data Excel using ASP.NET Core 2.1
Ok, Ta tạo một class Product.cs trong thư mục Models, để dùng lưu dữ liệu theo dạng danh sách List<Product>
+ Models/Product.cs

public class Product
    {
        public int idProduct { get; set; }
        public string Title { get; set; }
        public string UrlImage { get; set; }
        public string Detail { get; set; }
        public int Price { get; set; }


    }

Tạo file ExcelController.cs trong thư mục Controllers như sau:


using ExcelDataReader;
using ReadExcel.Models;
namespace ReadExcel.Controllers
{
    public class ExcelController : Controller
    {
        private readonly IHostingEnvironment _appEnvironment;

        public ExcelController(IHostingEnvironment appEnvironment)
        {
            this._appEnvironment = appEnvironment;
        }
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Index(IFormCollection collection)
        {
            if (ModelState.IsValid)
            {
                var files = HttpContext.Request.Form.Files;
                List<Product> products = new List<Product>();
                foreach (var item in files)
                {
                    if (item.Length > 0 && item!=null)
                    {
                        string file_name = Guid.NewGuid().ToString().Replace("-", "")+"_"+item.FileName;
                        string uploads = Path.Combine(_appEnvironment.WebRootPath, "files");
                        string urlPart = uploads + "/" + file_name;
                        string extension = Path.GetExtension(urlPart);
                        if(extension ==".xls" || extension == ".xslx")
                        {
                            using (var fileStream = new FileStream(Path.Combine(uploads, file_name), FileMode.Create))
                            {
                                await item.CopyToAsync(fileStream);                                
                            }
                            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                            using (var stream = System.IO.File.Open(urlPart, FileMode.Open, FileAccess.Read))
                            {
                                using (var reader = ExcelReaderFactory.CreateReader(stream))
                                {
                                    do
                                    {
                                        if (reader.Name == "page1" || reader.Name == "page2")
                                        {
                                            while (reader.Read())
                                            {
                                                products.Add(new Product
                                                {
                                                    idProduct = int.Parse(reader.GetValue(0).ToString()),
                                                    Title = reader.GetValue(1).ToString(),
                                                    UrlImage = reader.GetValue(2).ToString(),
                                                    Price = int.Parse(reader.GetValue(3).ToString()),
                                                    Detail = reader.GetValue(4).ToString()
                                                });
                                            }
                                        }
                                    } while (reader.NextResult());
                                }

                            }

                        }

                    }
                }
                if (products.Count > 0)
                {
                    //return Json(products);
                    ViewBag.products = products;
                    return View();
                }
                return RedirectToAction(nameof(Index));
               
            }
            return RedirectToAction(nameof(Index));
        }
    }
}

- Chúng ta cần using ExcelDataReader để có thể sử dụng được ExcelDataReader
- Dùng IHostingEnvironment để có thể gọi tới thư mục wwwroot 
- item.CopyToAsync(fileStream): Copy file vừa upload đến thư mục wwwroot/files
- List<Product> products: Tạo danh sách chưa dữ liệu đọc file excel
- reader.Name == "page1" : là name Sheet trong file Excel, tùy bạn đặt tên chỉ định để lấy
- reader.GetValue(): dùng để lấy giá trị trong file excel
- reader.NextResult(): sau khi đọc hết Sheet page1, sẽ chạy kế tiếp Sheet page2
 

Read Data Excel using ASP.NET Core 2.1

Tạo Index.cshtml trong thư mục Views/Excel 

+ Views/Excel/Index.cshtml

@model IEnumerable<Product>
@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
    <div class="col-md-8">
        <h2>Read file</h2>
        <form asp-controller="Excel" asp-action="Index" enctype="multipart/form-data">
           @Html.AntiForgeryToken()
            <div class="form-group">
                <label>Choose excel file</label>
                <input type="file" name="file" class="form-control"/>
            </div>
            <div class="form-group">
                <input type="submit" name="submit" value="Upload"/>
            </div>
        </form>
    </div>
    <div class="col-md-8">
        @if(ViewBag.products!=null)
        {
            <table class="table">
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th>UrlImage</th>
                    <th>Price</th>
                    <th>Detail</th>
                </tr>
                @foreach(var item in ViewBag.products)
                {
                    <tr>
                        <td>@item.idProduct</td>
                        <td>@item.Title</td>
                        <td>@item.UrlImage</td>
                        <td>@item.Price</td>
                        <td>@item.Detail</td>
                    </tr>
                }
            </table>
        }
    </div>
</div>

+ Startup.cs chỉnh lại để gọi ExcelController.cs

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Excel}/{action=Index}/{id?}");
            });

Demo:

Read Data Excel using ASP.NET Core 2.1

Github:Read Data Excel using ASP.NET Core 2.1

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)