如何获取特定列中的所有单元格?

时间:2016-03-16 14:02:41

标签: c# excel linq openxml

我有一个从单元格获取数据的程序,然后在单独的应用程序中记录这些信息。以下是用于细胞提取的代码片段。

TableStructure tableStructure = new tableStructure();
tableStructure.TableCols = {"A","B","C","D","E","F","G","H","I","J","K","L","M"};
tableStructure.StartRow = 1;
tableStructure.EndRow = 4001;
foreach (var colName in tableStructure.TableCols)
{
    for (var ci = tableStructure.StartRow; ci <= tableStructure.EndRow; ci++)
    {
        var addressName = colName + ci;
        Cell currentCell = wsPart.Worksheet.Descendants<Cell>().Where(c => c.CellReference == addressName).FirstOrDefault();//52000 times
        //some other scripts
    }
}


从这段代码中我可以得到我想要的输出,但是存在性能问题。对于上面的例子,仅需9分钟即可获得细胞。如果我评论以下一行,则只需50秒 Cell currentCell = wsPart.Worksheet.Descendants<Cell>().Where(c => c.CellReference == addressName).FirstOrDefault();
我想优化我的代码,就像有一个LINQ,我可以通过它获得所有的单元格 Descendants<Row>().FirstOrDefault(p => p.RowIndex == rowIndex)我现在的问题是,有没有上面的方法我可以从中获取特定列的所有单元格。

1 个答案:

答案 0 :(得分:0)

试试这个:

IEnumerable<Cell> cells = wsPart.Worksheet.Descendants<Cell>().Where(c => string.Compare(GetColumnName(c.CellReference.Value),
addressName, true) == 0).OrderBy(r => GetRowIndex(r.CellReference));

foreach (var cell in cells)
{

}