1. 程式人生 > 其它 >C# Excel轉化為List(自定義Excel表頭)

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);

六、資料格式