如何通过excel文件中的工作表和rowindex获取特定行

时间:2017-06-22 10:46:06

标签: c# excel row cell

我需要使用openXML在excel文件中选择一个特定的单元格:

Worksheet workSheet = workSheetPart.Worksheet;
Cell cell = GetCell(workSheet, "B", 2);


private static Cell GetCell(Worksheet worksheet,
  string columnName, uint rowIndex)
    {
        Row row = GetRow(worksheet, rowIndex);

        if (row == null)
            return null;

        return row.Elements<Cell>().Where(c => string.Compare
               (c.CellReference.Value, columnName +
               rowIndex, true) == 0).First();
    }

private static Row GetRow(Worksheet worksheet, uint rowIndex)
    {
        var test = worksheet.GetFirstChild<SheetData>().
          Elements<Row>().Where(r => r.RowIndex == rowIndex).First(); //Here is the problem. 

return worksheet.GetFirstChild<SheetData>().
          Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
    }

调试时我注意到RowIndex为null,所以这引起了我猜在linq查询中的问题

2 个答案:

答案 0 :(得分:0)

使用ElementAt ...

var test = worksheet.GetFirstChild<SheetData>().Elements<Row>().ElementAt(rowIndex);

答案 1 :(得分:0)

创建行时,必须为添加到excel中的每一行设置行索引值。

Row headerRow = new Row() { RowIndex = new UInt32Value(1) }; //Here I used as 1(one), use accordingly

创建单元格时,必须为创建的每个单元格设置CellReference值。

  Cell cell = new Cell() { };
  cell.CellReference = new StringValue("A1");
  cell.DataType = CellValues.String;
  cell.CellValue = new CellValue("Test value");

如果未设置行索引和单元格引用,则在其中查询时,这些值将为null。

在excel中使用的其他一些有用方法

 //To get the CellReference
 private static string GetExcelCellReference(uint columnNumber, uint rowNumber)
    {
        return $"{GetExcelColumnName(columnNumber)}{rowNumber}";
    }

    //To get the excel column name using column number
    private static string GetExcelColumnName(uint columnNumber)
    {
        int dividend = (int)columnNumber;
        string columnName = String.Empty;
        int modulo;

        while (dividend > 0)
        {
            modulo = (dividend - 1) % 26;
            columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
            dividend = (int)((dividend - modulo) / 26);
        }

        return columnName;
    }

    //To get the excel column name from cellname or cellreference number
    private static string GetColumnName(string cellName)
    {
        // Create a regular expression to match the column name portion of the cell name.
        Regex regex = new Regex("[A-Za-z]+");
        Match match = regex.Match(cellName);

        return match.Value;
    }

    //To get the row index from cell name or cell reference number
    private static uint GetRowIndex(string cellName)
    {
        // Create a regular expression to match the row index portion the cell name.
        Regex regex = new Regex(@"\d+");
        Match match = regex.Match(cellName);

        return uint.Parse(match.Value);
    }