XSSFSheet getLastRow() 有效但获取 lastrow return null 的单元格

XSSFSheet getLastRow() works but get the cells of lastrow return null

测试测试测试测试测试测试 1 2 3 4 5 6 $细胞 $细胞 $细胞 $细胞 $细胞 $细胞

代码如下:

File file = new File("mytemplate.xlsx");
FileInputStream filein = new FileInputStream(file);

XSSFWorkbook wb = new XSSFWorkbook(filein);
filein.close();
XSSFSheet sheet = wb.getSheetAt(0);
int lastrow = sheet.getLastRowNum();
int phyrow = sheet.getPhysicalNumberOfRows();

XSSFRow modlrow = sheet.createRow(lastrow);----still work, modlrow = 2
System.out.println(sheet.getRow(0).getCell(2));---still work
System.out.println(sheet.getRow(1).getCell(2));  ---still work
System.out.println(sheet.getRow(lastrow).getCell(2)+"=========");don't work

你的问题是这两行:

XSSFRow modlrow = sheet.createRow(lastrow);----still work, modlrow = 2
System.out.println(sheet.getRow(lastrow).getCell(2)+"=========");don't work

第一个创建一个全新的空行。第二个尝试在没有创建的情况下连续读取特定单元格

您要么需要显式创建该单元格,例如:

XSSFRow modlrow = sheet.createRow(lastrow);
modlrow.createCell(2);
System.out.println(sheet.getRow(lastrow).getCell(2)+"=========");

或者使用 Missing Cell Policy 进行提取,以便按需为您创建不存在的单元格,例如:

XSSFRow modlrow = sheet.createRow(lastrow);
modlrow.createCell(2);
System.out.println(sheet.getRow(lastrow).getCell(2, MissingCellPolicy.CREATE_NULL_AS_BLANK)+"=========");