Bài 5: Import hàng hóa từ file excel
Chào các bạn.
Ở bài này chúng ta sẽ import hàng hóa từ một file excel.
1. Tạo file excel mẫu:
2. Tạo lớp ProductImporter
using DevExpress.ExpressApp; using DevExpress.Spreadsheet; using System; using System.Collections.Generic; using System.Linq; using YouSoft.Vn.Framework.Core.Extensions; using YouSoft.Vn.XAFCustom.Supports.Base; using YouSoft.Vn.XAFCustom.Supports.Extensions; namespace App.Module.Modules.Inventory.Entities { public class ProductImporter : ExcelImporterBase<Product> { public override int StaringRowIndex => 2; public override string SampleFilePath => @"ExcelTemplates\Products.xlsx"; List<string> productNames; public override bool OnStart(IObjectSpace os, ViewController controller, Workbook workbook) { base.OnStart(os, controller, workbook); productNames = os.GetObjectsQuery<Product>() .Select(p=>p.Name) .ToList(); return true; } public override bool OnFinish() { productNames.Dispose(); return base.OnFinish(); } public override bool OnRowStart(int rowIndex, ref string error) { //1. đọc tên hàng hóa var name=Sheet.GetCellValueString(Columns.Name, rowIndex); name = name?.Trim(); //2. Nếu tên hàng hóa không rỗng/null và không có trong csdl if (!name.IsNullOrWhiteSpace() ||!productNames.Contains(name) ) { //3. tạo mới hàng hóa var price = Sheet.GetCellValue<double>(Columns.Price, rowIndex, 0); new Product(Session) { //với tên ở trên Name=name, Price=price }; productNames.Add(name); } //đọc giá return true; } public static class Columns { public const char Name = 'A'; public const char Price = 'B'; } } }
Đăng ký lớp ở App.Module.cs
protected override void Register(IExcelImportService service) { base.Register(service); service.Register<ProductImporter>(); }Lưu ý, ở project chạy chương trình, nhớ có file mẫu ở trên.
Chạy chương trình
Các bạn có thể tham khảo chi tiết ở Video hướng dẫn
Có khó khăn gì thì comment bên dưới nhé.
Không có nhận xét nào:
Đăng nhận xét