我正在用Java和Apache POI库对接口进行编程。我在删除空白行时遇到问题。我的代码是:
public class ExcelDeleteRowsCols {
final short ROW_START = 0;
final short COL_START = 0;
public void deleteRows() {
try {
// Open file
FileInputStream inf = new FileInputStream("in.xls");
Workbook wb = WorkbookFactory.create(inf);
// Loop every sheets of workbook
for (Sheet sheet : wb){
// Loop every rows of this sheet
int lastIndex = sheet.getLastRowNum();
for (int i = ROW_START; i <= lastIndex; i++) {
if (sheet.getRow(i) == null || sheet.getRow(i).getCell(COL_START) == null || sheet.getRow(i).getCell(COL_START).toString().equals("")){
sheet.removeRow(sheet.getRow(i)); //sheet.shiftRows(i, lastIndex, 2);
}
}
}
// Save as in another file
FileOutputStream fileOut = new FileOutputStream("out.xls");
wb.write(fileOut);
fileOut.flush();
fileOut.close();
System.out.println("Finished!");
} catch (IOException ioe) {
System.out.println(ioe);
} catch (Exception e) {
System.out.println(e);
}
}
}
确切的问题是,在具有空单元格的行中显示异常消息java.lang.NullPointerException。我不明白 Excel范例:
“空单元格”第2行第3行第4行第5行“空单元格”第7行第8行第9行第10行第11行第12行第13行
当没有空单元格时,代码可以正常工作...
请你能帮我吗?
提前致谢。
我有这个xls文件:
我的目标是删除所有空行,对于这个问题,我认为最好的选择是Java中的OPI。代码是:
public class ExcelDeleteRowsCols {
final short ROW_START = 0;
final short COL_START = 0;
public void deleteRows() {
try {
// Open file
FileInputStream inf = new FileInputStream("in.xls");
Workbook wb = WorkbookFactory.create(inf);
// Loop every sheets of workbook
for (Sheet sheet : wb){
// Loop every rows of this sheet
int lastIndex = sheet.getLastRowNum();
for (int i = ROW_START; i <= lastIndex; i++) {
if (sheet.getRow(i) == null || sheet.getRow(i).getCell(COL_START) == null || sheet.getRow(i).getCell(COL_START).toString().equals("")){
sheet.removeRow(sheet.getRow(i));
}
}
}
// Save as in another file
FileOutputStream fileOut = new FileOutputStream("out.xls");
wb.write(fileOut);
fileOut.flush();
fileOut.close();
System.out.println("Finished!");
} catch (IOException ioe) {
System.out.println(ioe);
} catch (Exception e) {
System.out.println(e);
}
}
}
当行为空时,代码可以正常工作,但是问题是当行为null时(sheet.getRow(i)== null)。例如,在此xls的第2行,第12行,第15行和第16行中,您的值为null,然后它不会被删除,因为命令sheet.removeRow(sheet.getRow(i)); NullPointer引发和异常。
有什么办法可以删除值为空的行?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句