C# Excel轉化為List(自定義Excel表頭)


一、添加引用

using System.Data.OleDb;

二、創建CustomExecutingFilterAttribute

  public class CustomExecutingFilterAttribute: Attribute
  {
    public string Title { get; set; }

  }

三、創建一個Model

 public class test2
  {
    
    [CustomExecutingFilterAttribute(Title = "QD")]//Excel列頭標題名稱
    public string Name { get; set; }
    [CustomExecutingFilterAttribute(Title = "ID")]//Excel列頭標題名稱
    public string ID { get; set; }
  }

四、創建轉化方法

 /// <summary>
    /// 將Excel轉化為List
    /// </summary>
    /// <typeparam name="T">類型</typeparam>
    /// <param name="FilePath">文件路徑</param>
    /// <param name="SheetIndex">sheet頁</param>
    /// <returns></returns>
    public static List<T> ExcelLoadeToList<T>(string FilePath, int SheetIndex) where T : class
    {
      #region 將excel加載為DataTable
      string strConn = $"Provider=Microsoft.Ace.OleDb.12.0;data source={FilePath};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
      OleDbConnection conn = new OleDbConnection(strConn);
      conn.Open();
      DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
      string TableName = schemaTable.Rows[SheetIndex][2].ToString().Trim();

      string strExcel = $"select * from [{TableName}]";
      OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn);
      DataSet ds = new DataSet();
      myCommand.Fill(ds, "table1");

      #endregion

      List<T> tlist = Activator.CreateInstance<List<T>>();
      var dType = typeof(T);

      for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
      {
        T t = Activator.CreateInstance<T>();
        foreach (PropertyInfo dP in dType.GetProperties())
        {
          string ColumnName = dP.Name;
          //此字段是否使用了CustomExecutingFilterAttribute類
          if (dP.IsDefined(typeof(CustomExecutingFilterAttribute), false))
          {
            var attributes = dP.GetCustomAttributes();
            foreach (var attribute in attributes)
            {
              //這里的MaximumLength 最好用常量去做
              var AttriColumnName = (string)attribute.GetType().
                GetProperty("Title")?.
                GetValue(attribute);
              if (!string.IsNullOrWhiteSpace(AttriColumnName))
              {
                ColumnName = AttriColumnName;
              }
            }
            //Excel中是否包含此列名
            if (ds.Tables[0].Columns.Contains(ColumnName))
            {
              var val = ds.Tables[0].Rows[i][ColumnName]?.ToString();
              dP.SetValue(t, val);
            }
          }
        }
        tlist.Add(t);
      }

      return tlist;
    }

五、調用方法

        string filePath = @"C:\Users\Administrator\Desktop\test.xlsx";
        var srclist = ExcelHelper.ExcelLoadeToList<test2>(filePath,0);

六、數據格式

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM