在 DevExpress.Spreadsheet.CellRange 中使用行号和列号
在 DevExpress.Spreadsheet.CellRange 中使用行号和列号,不用计算是第几列
在 DevExpress.Spreadsheet 中,CellRange 类可以通过行号和列号来定义单元格范围。以下是几种完全使用行号和列号创建 CellRange 的方法:

1. 使用 FromLTRB 方法
csharp
// 使用 FromLTRB 方法 (左, 上, 右, 下 - 都是基于0的索引)
int topRow = 1;    // 第2行 (0-based)
int leftColumn = 0; // 第1列 (A列, 0-based)
int bottomRow = 3;  // 第4行
int rightColumn = 2; // 第3列 (C列)

CellRange range = worksheet.Range.FromLTRB(leftColumn, topRow, rightColumn, bottomRow);
2. 使用行列索引直接创建
csharp
// 直接使用行列索引 (都是基于0的)
int firstRow = 0;    // 第1行
int firstColumn = 0; // A列
int lastRow = 2;     // 第3行
int lastColumn = 1;  // B列

CellRange range = worksheet.Range[firstRow, firstColumn, lastRow, lastColumn];
3. 使用单元格引用字符串
虽然这不是纯数字,但你可以将行号列号转换为Excel风格的引用:

csharp
int row1 = 1, col1 = 0; // A2
int row2 = 3, col2 = 2; // C4

string ref1 = GetExcelReference(col1, row1); // "A2"
string ref2 = GetExcelReference(col2, row2); // "C4"

CellRange range = worksheet.Range[ref1 + ":" + ref2];

// 辅助方法:将列号和行号转换为Excel引用
string GetExcelReference(int column, int row)
{
    string colRef = "";
    do {
        colRef = (char)('A' + column % 26) + colRef;
        column /= 26;
    } while (column > 0);
    return colRef + (row + 1); // 行号在Excel中是1-based
}
4. 使用 Worksheet.Range 属性
csharp
// 获取单个单元格
CellRange singleCell = worksheet.Range[(int)rowIndex, (int)columnIndex];

// 获取范围
CellRange multiCellRange = worksheet.Range[
    (int)startRowIndex, 
    (int)startColumnIndex, 
    (int)endRowIndex, 
    (int)endColumnIndex
];
注意事项
DevExpress 中的行号和列号通常是基于0的索引(第1行=0,第1列=0)
某些方法可能使用1-based索引,所以使用时请参考具体文档
对于大量操作,直接使用行列索引比转换为Excel引用字符串更高效
示例:遍历指定范围内的单元格
csharp
int startRow = 1, startCol = 1; // B2
int endRow = 4, endCol = 3;     // D5

for (int r = startRow; r <= endRow; r++)
{
    for (int c = startCol; c <= endCol; c++)
    {
        Cell cell = worksheet.Cells[r, c];
        // 处理单元格...
    }
}

渝公网安备 50011902000225号

渝ICP备18008233号-1