如何使用Apache poi从Excel文件中读取空白单元格AS String

时间:2021-02-27 20:23:12

I am new to Apache POI. I want to Read the blank cells as well. This is what I tried to achieve my objective but it problem is that it doesn't continue reading after getting a blank cell.

我是Apache POI的新手。我也想读取空白单元格。这是我试图实现我的目标,但问题是它在获得空白单元格后不会继续读取。

here is my logic

这是我的逻辑

HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow row;
            HSSFCell cell = null;
            Iterator<Row> rows = sheet.rowIterator();
             while (rows.hasNext()) {


                    row = (HSSFRow) rows.next();
                     if (row.getRowNum() == 0) {
                            continue;
                    } 
                    Iterator cells = row.cellIterator();
                    while(cells.hasNext()){
                        HSSFCell myCell = (HSSFCell) cells.next();
               if(myCell.getCellType()!=Cell.CELL_TYPE_STRING){
                           myCell.setCellType(Cell.CELL_TYPE_STRING);

                       }

Any suggestions?

1 个解决方案

#1


1  

Blank cells are not returned in iterators. Quoting Poi's quick guide:

迭代器中不返回空单元格。引用Poi的快速指南:

Note that a rowIterator and cellIterator iterate over rows or cells that have been created, skipping empty rows and cells.

请注意,rowIterator和cellIterator迭代已创建的行或单元格,跳过空行和单元格。

Another option is to iterate through each cell with

另一个选择是迭代每个单元格

row.getCell(i) 

and check if null or its type is Cell.CELL_TYPE_BLANK

并检查null或其类型是否为Cel​​l.CELL_TYPE_BLANK

You can get the last and first row numbers from Sheet's methods

您可以从Sheet的方法中获取最后一行和第一行数

sheet.getFirstRowNum()
sheet.getLastRowNum() 

Same for first and last column using row's methods

使用行的方法对第一列和最后一列相同

row.getFirstCellNum()
row.getLastCellNum()

#1


1  

Blank cells are not returned in iterators. Quoting Poi's quick guide:

迭代器中不返回空单元格。引用Poi的快速指南:

Note that a rowIterator and cellIterator iterate over rows or cells that have been created, skipping empty rows and cells.

请注意,rowIterator和cellIterator迭代已创建的行或单元格,跳过空行和单元格。

Another option is to iterate through each cell with

另一个选择是迭代每个单元格

row.getCell(i) 

and check if null or its type is Cell.CELL_TYPE_BLANK

并检查null或其类型是否为Cel​​l.CELL_TYPE_BLANK

You can get the last and first row numbers from Sheet's methods

您可以从Sheet的方法中获取最后一行和第一行数

sheet.getFirstRowNum()
sheet.getLastRowNum() 

Same for first and last column using row's methods

使用行的方法对第一列和最后一列相同

row.getFirstCellNum()
row.getLastCellNum()