2011年8月24日 星期三

[ASP.NET] Import Excel with linqtoexcel

上篇文章比較了以NPOI and EPPlus匯出Excel的效能,接著就是要介紹Import Excel了,雖然NPOI也可以Import Excel2003/2007,但我認識了linqtoexcel後,就毅然決然的選用LinqToExcel為我的Import利器了。
LinqToExcel為32位元的dll,所以如果在64位元遇到complier的問題時,請參閱轉載自網路的排除方法。 還有注意事項,轉載自官網:
Target x86 Platform Linq to Excel requires any projects referencing it to be built against the x86 platform target. See this link for detailed information on setting the platform target to x86. Note this only applies to compiling the project on x64 computers.
.Net 4 When using Linq to Excel in a .Net 4 app, make sure to change the target framework from the default client profile to the full .Net 4 framework. (Properties -> Application -> Target framework) The client profile cannot compile .Net 3.5 dlls.
檢而言之,只能跑在x64,跟.Net framework 3.5。 接著用官網的sample code介紹這好用的工具。
var excel = new ExcelQueryFactory("excelFileName");
var oldCompanies = from c in repo.Worksheet("US Companies") //worksheet name = 'US Companies'
                   where c.LaunchDate < new DateTime(1900, 0, 0)
                   select c;
首先讀取名字為"US Companies"的工作表,如果無法確定上傳的檔案的名稱,最好傳入index即可。
接著<Company>則是有一個名叫Company的Class與Excel 的欄位都一模一樣, 這樣檔案就會乖乖的資料吃到Company的集合物件, 並可以用linq的手法去做資料篩選,一整個就是美妙。

不過如果Excel欄位與Class無法設定成一樣的,那還是有法可解:
var excel = new ExcelQueryFactory("excelFileName");
excel.AddMapping(x => x.State, "Providence"); //maps the "State" property to the "Providence" column

var indianaCompanies = from c in excel.Worksheet()
                       where c.State == "IN" && c.Employees > 500
                       select c;
使用AddMapping去指定欄位間的關係,Excel欄位 "Providence"去指定對應到Company的State的欄位。

沒有留言:

張貼留言