以程式方式讀取Excel的另一項選擇-Linq to Excel
要使用LINQ to Excel必須先到Google Project Hosting上下載LinqToExcel組件(截至本文撰寫為止最新版本為1.5.3),解壓縮後依照下列步驟進行相關設定:
- 必須加入下列參考:
-
- LinqToExcel.dll
- Remotion.dll
- Remotion.Data.Linq.dll
- 建議匯入下列命名空間:
-
- LinqToExcel
- Remotion
下列程式碼示範如何以LINQ to Excel讀取Excel,下圖為EXCEL檔案的內容:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7: using LinqToExcel;
8: using Remotion;
9:
10: namespace WebApplication2
11: {
12: public partial class Linq2Excel : System.Web.UI.Page
13: {
14: protected void Page_Load(object sender, EventArgs e)
15: {
16: ExcelQueryFactory excel = new ExcelQueryFactory(@"E:\Book1.xlsx");
17: int WorksheetCount = excel.GetWorksheetNames().Count();
18: string row = string.Empty;
19: List<object> cell = new List<object>();
20:
21: if (WorksheetCount > 0)
22: {
23: IQueryable<Row> query = from p in excel.Worksheet(0)
24: select p;
25: foreach (Row item in query)
26: {
27: int j = 0;
28: foreach (string col in item.ColumnNames)
29: {
30: if (string.IsNullOrEmpty(row))
31: row = col + "={" + j.ToString() + "}";
32: else
33: row += "," + col + "={" + j.ToString() + "}";
34: cell.Add(item[j]);
35: j++;
36: }//for col
37: Response.Write(string.Format(row, cell.ToArray()) + "<br/>");
38: row = string.Empty;
39: cell.Clear();
40:
41: }//for item
42: }//for WorksheetCount
43: }
44: }
45: }
上述程式碼的第16列使用ExcelQueryFatory物件來讀取EXCEL檔案,接著第17列用GetWorkSheetNames方法取得工作表(Sheet)並計算工作表的數量,若工作表數量大於0才透過第23列的LINQ查詢取得該工作表的所有資料,接著以第28列的ColumnNames屬性來取得每個儲存格的名稱,最後將每一列的結果以string.Format方法來格式化顯示的結果(執行結果如下圖)。
PS:印象中NPOI只支援EXCEL 97-2003的格式,若要以程式方式讀取EXCEL 2007以上的格式不妨可以考慮使用LINQ To Excel,另外CodePlex亦有專案在開發LINQ to Excel的函式庫(Excel.Linq)但尚未Release,程式碼片段如下,
1: using(XlsWorkbook book = new XlsWorkbook("TestData\\100.xls")) {
2: var sheets = from s in book.Worksheets
3: where s.Name == "100"
4: select s;
5: foreach(var sheet in sheets) Console.WriteLine(sheet.Name);
6: }
參考資料: