如何通过Excel文件中的工作表和行索引获取特定行

问题描述 投票:0回答:2

我需要通过使用 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 为空,所以这导致了我猜测 linq 查询中的问题

c# excel row cell
2个回答
0
投票

使用 ElementAt...

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

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");

如果没有设置行索引和单元格引用,则查询时值为空。

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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.