Apache POI空白值

Bhu*_*han 2 java apache-poi

我使用Apache POI从导入数据excel filedatabase.(新手到Apache POI)

我允许用户从Excel工作表中选择列并将这些列映射到数据库列.映射列后,当我尝试将记录插入ExcelDatabase那时:

  • 如果其中包含NO blank值的列已映射,则将正确数据插入到数据库中
  • 如果列映射了其中的BLANK值,则如果a Excel Cell具有空值,column则分配该值的前一个值.

源代码:

FileInputStream file = new FileInputStream(new File("C:/Temp.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file); //Get the workbook instance for XLS file
HSSFSheet sheet = workbook.getSheetAt(0);   //Get first sheet from the workbook
Iterator<Row> rowIterator = sheet.iterator(); //Iterate through each rows from first sheet
while (rowIterator.hasNext())
{
  HSSFRow hssfRow = (HSSFRow) rowIterator.next();
  Iterator<Cell> iterator = hssfRow.cellIterator();
  int current = 0, next = 1;
  while (iterator.hasNext())
  {
    HSSFCell hssfCell = (HSSFCell) iterator.next();
    current = hssfCell.getColumnIndex();
    for(int i=0;i<arrIndex.length;i++)    //arrayIndex is array of Excel cell Indexes selected by the user
    {
      if(arrIndex[i] == hssfCell.getColumnIndex())
      {
        if(current<next) 
        {
                    //System.out.println("Condition Satisfied");     
        }
        else 
        {
          System.out.println( "pstmt.setString("+next+",null);");
          pstmt.setString(next,null);
          next = next + 1;
        }
        System.out.println( "pstmt.setString("+next+","+((Object)hssfCell).toString()+");");
        pstmt.setString(next,((Object)hssfCell).toString());
        next = next + 1;
      }
    }
  }
  pstmt.addBatch();
  }
Run Code Online (Sandbox Code Playgroud)

我在SO上寻找类似的问题,但仍然无法解决问题..所以任何帮助将不胜感激.

提前致谢..

Gag*_*arr 6

你犯了一个非常常见的错误,这个错误在很多过去的StackOverflow问题中都有所涉及

正如关于单元迭代Apache POI文档所说

在某些情况下,在迭代时,您需要完全控制缺失或空白单元格的处理方式,并且您需要确保访问每个单元格而不仅仅是文件中定义的单元格.(CellIterator将仅返回文件中定义的单元格,主要是具有值或样式的单元格,但它取决于Excel).

听起来你处于这种情况,你需要关心每一行/细胞,而不只是抓住所有可用的细胞而不必担心差距

您需要将代码更改为有点像POI文档中的示例:

// Decide which rows to process
int rowStart = Math.min(15, sheet.getFirstRowNum());
int rowEnd = Math.max(1400, sheet.getLastRowNum());

for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
   Row r = sheet.getRow(rowNum);

   int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT);

   for (int cn = 0; cn < lastColumn; cn++) {
      Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
      if (c == null) {
         // The spreadsheet is empty in this cell
         // Mark it as blank in the database if needed
      } else {
         // Do something useful with the cell's contents
      }
   }
}
Run Code Online (Sandbox Code Playgroud)