首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

通用高擴展性 Excel 匯入實作:支援多欄名對應、跨欄填充與資料驗證

     編輯:關於.NET

背景與痛點

Excel 匯入資料庫是企業應用常見功能。傳統做法:Excel → DataTable → List<T> → 資料庫。雖然通用 ExcelUtil 基類常提供 GetEntityListFromFile<T>(string fileName) 方法,但多為機械式一對一欄位對應,缺乏彈性,實務上常遇到以下挑戰:

  • 同一欄位對應多個欄名:客戶未使用標準模板或版本不一,導致同一實體屬性(如 ID)在 Excel 中可能出現「ID」、「編號」等不同欄名。
  • 單一 Excel 欄位需填充多個實體屬性:例如 Excel 僅有「ID」,需透過 ID 從資料庫查詢對應的「Name」填充實體。
  • 複雜資料驗證需求:包含資料型別檢查、資料庫存在性驗證、狀態有效性驗證等多層次規則。

架構設計:基於配置與策略模式的通用匯入引擎

核心介面定義

public interface IExcelImporter<T> where T : class, new()
{
    ImportResult<T> Import(Stream excelStream, ImportContext context);
}

public class ImportContext
{
    public Dictionary<string, string> ColumnAliasMap { get; set; } // 欄位別名對應
    public List<IColumnResolver> ColumnResolvers { get; set; }     // 自定義欄位解析器
    public List<IDataValidator<T>> Validators { get; set; }        // 資料驗證器鏈
}

public interface IColumnResolver
{
    bool CanResolve(string columnName, PropertyInfo targetProperty);
    object ResolveValue(string rawValue, ImportContext context, PropertyInfo targetProperty);
}

public interface IDataValidator<T>
{
    ValidationResult Validate(T entity, int rowIndex);
}

關鍵實作細節

  1. 彈性欄位對應:透過 ColumnAliasMap 將多個 Excel 欄名映射至同一實體屬性,解析時優先嘗試別名匹配。
  2. 跨欄填充解析器:實作 IColumnResolver,例如 ForeignKeyResolver 可根據某欄值查詢資料庫並回填多個屬性。
  3. 管道式驗證:驗證器採用責任鏈模式,支援型別轉換、必填、唯一性、業務規則等多層驗證,錯誤資訊攜帶列號回報。
  4. 錯誤容錯與報表:匯入結果包含成功實體清單、錯誤明細(列號、欄位、錯誤訊息),支援產生錯誤報表 Excel 回饋給使用者。

使用範例

var importer = new ExcelImporter<ProductImportDto>();
var context = new ImportContext
{
    ColumnAliasMap = new Dictionary<string, string>
    {
        { "產品編號", "ProductId" },
        { "ID", "ProductId" },
        { "品名", "ProductName" }
    },
    ColumnResolvers = new List<IColumnResolver>
    {
        new ForeignKeyResolver("CategoryId", "CategoryName", 
            id => categoryService.GetNameById(id))
    },
    Validators = new List<IDataValidator<ProductImportDto>>
    {
        new RequiredFieldValidator<ProductImportDto>(d => d.ProductId),
        new DuplicateValidator<ProductImportDto>(d => d.ProductId),
        new BusinessRuleValidator<ProductImportDto>(d => 
            d.Price > 0, "價格必須大於零")
    }
};

var result = importer.Import(excelStream, context);
if (result.HasErrors)
{
    // 輸出錯誤報表或顯示前端
    ExportErrorReport(result.Errors);
}
else
{
    productService.BulkInsert(result.Entities);
}

擴展性優勢

  • 零程式碼擴展新實體:新增 DTO 與配置即可支援新匯入類型,無需修改核心邏輯。
  • 驗證規則可組合:業務驗證獨立封裝,可跨專案復用。
  • 支援多種 Excel 格式:底層採用 NPOI/EPPlus 抽象,相容 .xls/.xlsx。

總結

透過「配置驅動 + 策略模式 + 管道驗證」架構,將 Excel 匯入從僵化的欄位對應升級為可應對複雜業務場景的通用引擎,大幅降低維護成本並提升系統健壯性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved