Java的Apache POI空白单元格

我是Apache POI的新手,但并不是Java的新手。 我试图将数据从一个Excel文件转换到另一个,将任何分隔符数据更改为新的单元格。 尽pipe大部分新数据都是正确的,但是有一些例外情况并没有遵循空白单元格的规则。 这里是input文件https://ufile.io/bce15 ,这里是输出文件https://ufile.io/55020

在下面的图片logging4和5是不是玩的规则,我不知道为什么!

在这里输入图像说明

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; public class testWrite { public static void main( String [] args ) { int rowNums = 1; try { FileInputStream file = new FileInputStream(new File("ExceptionDataDummy.xlsx"));; XSSFWorkbook wb = new XSSFWorkbook(file); XSSFSheet sheet = wb.getSheetAt(0); String filename = "ExceptionDataResult.xlsx" ; XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet1 = workbook.createSheet("FirstSheet"); Iterator<Row> rows = sheet.rowIterator(); int col = 0; while( rows.hasNext() ) { XSSFRow row = (XSSFRow) rows.next(); XSSFRow row1 = sheet1.createRow((short)rowNums); System.out.println("\n"); Iterator<Cell> cells = row.cellIterator(); while( cells.hasNext() ) { XSSFCell cell = (XSSFCell) cells.next(); if(XSSFCell.CELL_TYPE_NUMERIC==cell.getCellType()) { row1.createCell(col).setCellValue(cell.getNumericCellValue()); col++; } else if(XSSFCell.CELL_TYPE_STRING==cell.getCellType()){ String contents = cell.getStringCellValue(); String[] items = contents.split(","); for (String item : items) { row1.createCell(col).setCellValue(item); col++; } } else if(XSSFCell.CELL_TYPE_BOOLEAN==cell.getCellType()) { row1.createCell(col).setCellValue(cell.getBooleanCellValue()); col++; } else if((cell.equals("")) || (XSSFCell.CELL_TYPE_BLANK==cell.getCellType()) || (cell == null)) { cell.setCellType(Cell.CELL_TYPE_BLANK); col++; } else { System.out.print("Unknown cell type"); } } rowNums++; col=0; } FileOutputStream fileOut = new FileOutputStream(filename); workbook.write(fileOut); fileOut.close(); System.out.println("Your excel file has been generated!"); wb.close(); workbook.close(); } catch ( IOException ex ) { ex.printStackTrace(); } } } 

在你的代码中,你正在使用cellIterator

 Iterator<Cell> cells = row.cellIterator(); 

cellIterator不包含空单元格。

您不必使用cellIterator,而必须从第一个单元格开始循环到最后一个单元格,然后检查单元格是否为空。

你可以参考下面的示例代码 –

 for (int colNum = 0; colNum < row.getLastCellNum(); colNum++) { Cell cell = row.getCell(colNum, Row.CREATE_NULL_AS_BLANK); String cellValue = null; // do whatever you want to do with the cell or its value }