2012-07-10 115 views
0

我從Excel表格中檢索單元格,這是我得到的輸出。使用foreach循環創建Excel表格中的列表

Cell A2 has value 113,295 
Cell B2 has value 540 
Cell C2 has value 41,044 
Cell A3 has value 192,653 
Cell B3 has value 510 
Cell C3 has value 41,037 

代碼:

 using (ExcelPackage package = new ExcelPackage(existingFile)) 
     { 
      ExcelWorksheet sheet = package.Workbook.Worksheets[1]; 

      //Select all cells in column d between 9990 and 10000 
      var query1 = (from cell in sheet.Cells["A2:C2"] select cell); 

      int count = 0; 
      string[] s = null; 

      foreach (var cell in query1) 
      { 
       Console.WriteLine("Cell {0} has value {1:N0}", cell.Address, cell.Value); 

      } 

我的問題是,我想創建一個類成員a,b和c和我想要一個列表<>持有這些對象的集合。

目前,它正在迭代,但我不知道for循環中的哪個單元是A,B或C.

回答

0

你可以寫一個分區方法,並給它排的長度......在你的案件3

IEnumerable<List<T>> Partition<T>(IEnumerable<T> col, int partitionSize) { 
if (col.Count() == 0) { 
    return new List<List<T>>(); 
} else { 
    var l = new List<List<T>>(); 
    l.Add(col.Take(partitionSize).ToList()); 
    return l.Concat(Partition(col.Skip(partitionSize), partitionSize)); 
} 
} 

class TheClass { 
public int A, B, C; 
} 

return Partition(sheet.Cells["A2:C2"], 3) 
     .Select(cells => new TheClass { 
      A = int.Parse(cells[0].Value), 
      B = int.Parse(cells[1].Value), 
      C = int.Parse(cells[2].Value) 
     }); 

我希望這有助於