java excel 空行_java使用poi删除excel中的空行
根據(jù)自己實際操作,poi中l(wèi)astRowNum方法獲取行數(shù)的是excel最后有數(shù)據(jù)的一行,從0開始
而physicalNumberOfRows方法獲取的行數(shù)是excel最后有數(shù)據(jù)的一行減去最后一行之前的空白行
工作中有一個需求是,上傳excel文件導入數(shù)據(jù),但是需要將成功的數(shù)據(jù)的條數(shù),和失敗條數(shù)返回,這種情況我的做法就是將成功的條數(shù)從excel中刪除,使用
sheet.removeRow(sheet.getRow(40));
但是這個方法我們刪除的只是數(shù)據(jù),當前行并沒有刪除,所以留下來的是一個空行
這種情況就需要將空行后邊的數(shù)據(jù)全部向前移一行,用到的方法是
sheet.shiftRows(i+1,physicalNumberOfRows,-1);
二個參數(shù)為需要移動的行的區(qū)間,第三個參數(shù)負數(shù)代表向前移,正數(shù)代表向后移
具體代碼:
FileInputStream fileInputStream = new FileInputStream("D:\\MyDocuments\\itw_renzm\\桌面\\file.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = workbook.getSheetAt(0);
int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
int lastRowNum = sheet.getLastRowNum();
//清除excel當前行
sheet.removeRow(sheet.getRow(10));
sheet.removeRow(sheet.getRow(20));
sheet.removeRow(sheet.getRow(21));
sheet.removeRow(sheet.getRow(22));
sheet.removeRow(sheet.getRow(23));
sheet.removeRow(sheet.getRow(24));
sheet.removeRow(sheet.getRow(40));
System.out.println(lastRowNum+"------"+physicalNumberOfRows);
for(int i =1;i
Row row = sheet.getRow(i);
Cell cell = null;
String cellValue = "";
if (row!=null){
cell = row.getCell(0);
cellValue = POIUtil.getCellValue(cell);
}
if (row==null||cell==null||cellValue==""){
sheet.shiftRows(i+1,lastRowNum,-1);
i--;
//減去一條空行,總行數(shù)減一。
lastRowNum--;
}
}
FileOutputStream fileOutputStream = new FileOutputStream("D:\\MyDocuments\\itw_renzm\\桌面\\file1.xls");
workbook.write(fileOutputStream);
fileOutputStream.close();
workbook.close();
fileInputStream.close();
}
總結
以上是生活随笔為你收集整理的java excel 空行_java使用poi删除excel中的空行的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2012 VS密钥
- 下一篇: 如何才能更好发挥WinRunner,实现