2

I am trying to delete all rows in an excel using the below code:

InputStream oFile=new FileInputStream(DefectExcel);
Workbook oWB= WorkbookFactory.create(oFile);     
Sheet sheet= oWB.getSheet(Sheet1);
Row oRow= sheet.getRow(i);

for (int i =0;i <=sheet.getLastRowNum(); i++) {
    sheet.removeRow(sheet.getRow(i));
    System.out.println("Row Deleted");
}

Also tried using the below code as well:

InputStream oFile=new FileInputStream(DefectExcel);
Workbook oWB= WorkbookFactory.create(oFile);     
Sheet sheet= oWB.getSheet(Sheet1);
Row oRow= sheet.getRow(i);
Iterator<Row> rowIte =  sheet.iterator();
while(rowIte.hasNext()){
    System.out.println("Row deleted");
    rowIte.next();              
    rowIte.remove();

In both the above code, its printing Row deleted number of times the available row but the row originally is still not deleted from the excel.

Can someone please help why the rows are still not deleted from the excel and how can I remove all the rows in the excel?

Smittey
  • 2,475
  • 10
  • 28
  • 35

1 Answers1

0

Your code is good and is removing rows from sheet but it won't reflect the changes in the original file unless you write those in new file or same file.

Here is the code :

FileInputStream fis = new FileInputStream(new File("file.xlsx"));
Workbook workbook = new XSSFWorkbook(fis);
fis.close();
.........<some code>......
..........................
FileOutputStream is = new FileOutputStream("file.xlsx");
workbook.write(is);
is.close();
Arpit Agarwal
  • 326
  • 3
  • 15