NPOI 获取指定范围的单元格

//返回指定范围单元格
public  ICellRange GetCellRange(ISheet ws, CellRangeAddress range)
{
    int firstRow = range.FirstRow;
    int firstColumn = range.FirstColumn;
    int lastRow = range.LastRow;
    int lastColumn = range.LastColumn;
    int height = lastRow - firstRow + 1;
    int width = lastColumn - firstColumn + 1;
    List temp = new List(height * width);
    for (int rowIn = firstRow; rowIn <= lastRow; rowIn++)
    {
        for (int colIn = firstColumn; colIn <= lastColumn; colIn++)
        {
            IRow row = ws.GetRow(rowIn);
            if (row == null)
            {
                row = ws.CreateRow(rowIn);
            }
            ICell cell = row.GetCell(colIn);
            if (cell == null)
            {
                cell = row.CreateCell(colIn);
            }
            temp.Add(cell);
        }
    }
    return SSCellRange.Create(firstRow, firstColumn, height, width, temp, typeof(HSSFCell));
}
int rowstart=1;    //开始行
int rowend=3;      //结束行
int colstart=2;    //开始列
int colend=5;      //结束列
IWorkbook wb = new XSSFWorkbook();
ISheet ws= wb.CreateSheet("Sheet1");
//获取范围单元格
ICellRange cellRange = GetCellRange(ws, new CellRangeAddress(rowstart, rowend, colstart, colend));
//遍历整个范围的单元格
foreach (ICell c in cellRange)
{
    
}

上述代码返回红色标识的单元格。

R1C2分别对应:rowstart,colstart

R3C5分别对应:rowend,colend

你可能感兴趣的:(C#,OFFICE)