【问题标题】:creating a list from excel sheet using foreach loop使用 foreach 循环从 excel 工作表创建列表
【发布时间】:2012-07-10 09:16:49
【问题描述】:

我正在从 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 的类,并且我想要一个 List 来保存这些对象的集合。

目前,它正在迭代,但我不知道 for 循环中哪个单元格是 A、B 或 C。

【问题讨论】:

    标签: c# excel foreach arraylist epplus


    【解决方案1】:

    您可以编写一个 Partition 方法并给它行的长度...在您的情况下 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)
             });
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多