You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 使用NPOI读取Excel时如何实现按列从上到下遍历单元格

错误原因

你改写的代码核心问题是行列索引混用:外层循环的变量i是列索引,你错误地用它作为行索引调用sheet.GetRow(i),导致行获取完全错位,且内层循环的行索引j全程没有用到,始终读取同一行的同一列内容,才会出现异常读取的问题。


正确实现逻辑

要实现按列从上到下读取,需要外层循环遍历列索引,内层循环遍历每一行的对应列,同时要提前计算工作表的最大列数,兼容部分行单元格数量不一致的场景,完整代码如下:

// 先计算工作表最大列数,兼容不同行单元格数量不一致的情况
int maxColumnNum = 0;
for (int r = sheet.FirstRowNum; r <= sheet.LastRowNum; r++)
{
    IRow row = sheet.GetRow(r);
    if (row != null && row.LastCellNum > maxColumnNum)
    {
        maxColumnNum = row.LastCellNum;
    }
}

List<string> resultList = new List<string>();
// 外层循环遍历所有列
for (int colIndex = sheet.GetRow(sheet.FirstRowNum).FirstCellNum; colIndex < maxColumnNum; colIndex++)
{
    // 内层循环遍历当前列的所有行
    for (int rowIndex = sheet.FirstRowNum; rowIndex <= sheet.LastRowNum; rowIndex++)
    {
        IRow row = sheet.GetRow(rowIndex);
        if (row == null) continue;
        // 跳过整行都是空白的行,和原有逻辑保持一致
        if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
        
        ICell cell = row.GetCell(colIndex);
        if (cell == null) continue;
        string cellValue = cell.ToString().Trim();
        if (!string.IsNullOrEmpty(cellValue))
        {
            resultList.Add(cellValue);
        }
    }
}

可选调整说明

  • 如果你需要跳过表头行,只需要把内层循环的起始值改为sheet.FirstRowNum + 1即可,和你原有行读取的逻辑保持一致
  • 如果需要按列分组存储内容,只需要在外层循环内每次新建一个列表存储当前列的内容即可

内容的提问来源于stack exchange,提问作者Platon Zvonkov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:24:03