Bài 6.a: Export dữ liệu ra file excel
Thân chào anh em YAFers. Hôm nay, chúng ta sẽ làm nội dung sau:
- Xuất dữ liệu hàng hóa (Product) ra file excel theo một mẫu định nghĩa trước.
Nội dung chi tiết các bạn có thể xem clip này nhé.
- Xuất dữ liệu hàng hóa (Product) ra file excel theo một mẫu định nghĩa trước
1.1 Định nghĩa mẫu file excel
Đầu tiên, các bạn tạ một file excel trong thư mục ExcelTemplates, có format như sau:
1.2 Tạo lớp Export
Sau đó tạo lớp export như bên dưới.
using DevExpress.ExpressApp; using DevExpress.Spreadsheet; using System; using System.Linq; using YouSoft.Vn.XAFCustom.Supports.Extensions; using YouSoft.Vn.XAFCustom.Supports.Interfaces; namespace App.Module.Modules.Inventory.Entities { public class ProductExcelFiller : IFillDataToExcelTemplate { public string RelativeFilePath => @"ExcelTemplates\BaoGia.xlsx"; public string DefaultSavingName => $"{DateTime.Now.ToString("ddMMyyy_HHmm")}_BaoGia.xlsx"; public Type TargetType => typeof(Product); public Nesting TargetNesting => Nesting.Any; public ViewType TargetViewType => ViewType.Any; public bool FillData(Worksheet sheet, ViewController controller, out string expectedExportFileName) { expectedExportFileName = DefaultSavingName; var products = controller.View.GetSelectedObjects<Product>(); if (products.Count <= 0) { products = controller.View.ObjectSpace.GetObjectsQuery<Product>() .ToList(); } var rowIndex = FillingInfo.StartingRow; var index = 1; foreach(var product in products) { sheet.SetCellValue($"{FillingInfo.STT}{rowIndex}", index.ToString()); sheet.SetCellValue($"{FillingInfo.Name}{rowIndex}", product.Name); sheet.SetCellValue($"{FillingInfo.Price}{rowIndex}", product.Price.ToString("N0")); rowIndex++; index++; } return true; } public class FillingInfo { public const int StartingRow = 5; public const char STT = 'A'; public const char Name = 'B'; public const char Price = 'C'; } } }
1.3 Đăng ký
//file: App.Module.cs protected override void Register(IFillDataToExcelTemplateService service) { base.Register(service); service.Register<ProductExcelFiller>(); }
1.4 Chạy phần mềm
Kết quả sau khi xuất.
Chúc các bạn thành công.
Không có nhận xét nào:
Đăng nhận xét