zoukankan      html  css  js  c++  java
  • 解决c# npoi 导入 中间单元格未激活 ,对应datatable 顺序混乱的问题.或nopi 单元格中间 null 空值 null 空值 后续读取不到问题

    场景:今天做一个导入功能,通用的npoi 导入代码,都是 先准备好一个datatable ,绘制标题列,然后遍历excel ,循环赋值 .

    正常情况下,如果表格内都有值,或者是 空字符串单元格也可以,即 所有单元格都是激活状态.读取正常

    常用代码这样:

      int rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)
                        {
                            IRow row = sheet.GetRow(i);
                            if (row == null || row.Cells.Count == 0) continue; //没有数据的行默认是null       
    
                            DataRow dataRow = data.NewRow();
    
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                    dataRow[j] = row.Cells[j];
                                // Convert.ToDateTime();
                            }
    
                            data.Rows.Add(dataRow);
                        }
                    }
    
    
    

    但是如果中间有未激活的代码 if (row.GetCell(j) != null) 这句就出错了,因为假如24列,但是中间有2个未激活单元格,那sheet.GetRow(i);

    只有 22列,所以代码运行到这就出错,而且会导致table不对应赋值.
    解决方法如下:

     
      //最后一列的标号
                        int rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)
                        { 
                            IRow row = sheet.GetRow(i);  
                            if (row == null || row.Cells.Count == 0) continue; //没有数据的行默认是null       
    
                            DataRow dataRow = data.NewRow(); 
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                try
                                {
                                    //防止中间有未激活的单元格  用row.GetCell(j) != null 判定空最后一个无效,不知道什么原因,所以用try
                                    int ColumnIndex = row.Cells[j].ColumnIndex; //获取真正的列索引,防止列混乱,否则对应datatable列错误
                                    dataRow[ColumnIndex] = row.Cells[j];
                                    //if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                    //    dataRow[j] = row.Cells[j];
                                }
                                catch 
                                { }
                                // Convert.ToDateTime();
                            }
    
                            data.Rows.Add(dataRow);
                        }
    

      

  • 相关阅读:
    C++ UFT-8和GB2312间的转换
    ssh不输入密码
    thinkpad T480安装WIN7
    删除目录下的不规则文件
    使用组合的方式来创建新类, 并可以重新定制某些类的特定行为
    使用gradle 编译生成 apk出现的问题
    android studio 使用 SVN
    Fiddler 抓取 Genymotion 数据包
    在eclipse中查看android源代码
    计算 md5
  • 原文地址:https://www.cnblogs.com/efreer/p/12100539.html
Copyright © 2011-2022 走看看