XCode讀取Excel資料並適用於任何資料庫

來源:互聯網
上載者:User

XCode讀取Excel資料並適用於任何資料庫是本文要介紹的內容,不多說,直接進入話題。雖然是充血模型,雖然是強型別,XCode同樣支援遍曆任何資料庫結構,並以強型別相對於DataSet等字典訪問)方式讀取資料。

要遍曆資料庫結構是很容易的事情,絕大多數Orm都支援。

但是在沒有實體類的情況下以強型別方式讀取資料,就稍微有些複雜。XCode的原理是為每張表動態建立繼承自Entity<>的實體類,然後通過介面來操作實體類。

代碼中有了快速反射,雖然沒有效能損耗,但是用起來挺彆扭的,這裡說明了XCode對於實體類別中繼資料的動態訪問支援還不夠。

 
  1. // 添加一個串連  
  2. DAL.AddConnStr("test", "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=Test.xls;" + "Extended Properties=Excel 8.0;", null, null);  
  3. DAL dal = DAL.Create("test");  
  4. // 遍曆所有表  
  5. foreach (XTable table in dal.Tables)  
  6. {  
  7.     Console.WriteLine("表 {0}:", table.Name);  
  8.     // 建立一個實體操作者,這裡會為資料表動態產生一個實體類,並使用CodeDom編譯  
  9.     IEntityOperate op = dal.CreateOperate(table.Name.Replace("$", null));  
  10.     // 因為動態產生代碼的缺陷,表名中的$已經被去掉,並且Excel的查詢總必須給表名加上方括弧,還是因為有$  
  11.     // 下面通過快速反射設定Meta.TableName  
  12.     Type type = op.GetType();  
  13.     type = typeof(Entity<>.Meta).MakeGenericType(type);  
  14.     PropertyInfoX.Create(type, "TableName").SetValue("[" + table.Name + "]");  
  15.     // 如果沒有記錄,跳過  
  16.     if (op.FindCount() < 1) continue;  
  17.      // 輸出表頭  
  18.     foreach (FieldItem item in op.Fields)  
  19.     {  
  20.         if (item.Name.StartsWith("F")) break;  
  21.  
  22.         Console.Write("{0}\t", item.Name);  
  23.     }  
  24.     Console.WriteLine();  
  25.     // 尋找所有資料  
  26.     EntityList<IEntity> list = op.FindAll();  
  27.     //DataSet ds = list.ToDataSet();  
  28.     // 輸出資料  
  29.     foreach (IEntity entity in list)  
  30.     {  
  31.         foreach (FieldItem item in op.Fields)  
  32.         {  
  33.             if (item.Name.StartsWith("F")) break;  
  34.  
  35.             Console.Write("{0}\t", entity[item.Name]);  
  36.         }  
  37.         Console.WriteLine();  
  38.     }  

小結:XCode讀取Excel資料並適用於任何資料庫的內容介紹完了,希望本文對你有所協助!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.