user2496503
user2496503

Reputation: 927

Delete multiple Rows containing a specific String

I've been trying to develop a code that can delete multiple rows containing a specific String "POST". I have been doing this like:

 private void processExcelFile(File f_path){
    File path=f_path;
    HSSFWorkbook wb = null;
    try{   
        FileInputStream is=new FileInputStream(path);

        wb= new HSSFWorkbook(is);
        HSSFSheet sheet = wb.getSheetAt(0);
        int j = 0;

        for(Row row: sheet){
           for(Cell cell : row){
               count++;
                   if (cell.getCellType() == Cell.CELL_TYPE_STRING){
                       if (cell.getRichStringCellValue().getString().trim().contains("POST")){
                           rowcount_post=row.getRowNum();
                           System.out.print("ROW COUNT= "+rowcount_post);
                           HSSFRow removingRow = sheet.getRow(rowcount_post);

                           if (removingRow != null) {
                               sheet.removeRow(removingRow);
                           }
                       }
                   }
               }
           }
       } catch(Exception e){
           JOptionPane.showMessageDialog(this,e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
       }

       try{
           FileOutputStream fileOut = new FileOutputStream("C:/juni.xls");
           wb.write(fileOut);
       } catch(Exception e) {
           JOptionPane.showMessageDialog(this,e.getMessage(),"SAVE Error",JOptionPane.ERROR_MESSAGE);
       }
   }

It is a matter of fact that it only deletes one row at a time. Is it possible that I could delete all the rows containing the String POST?

Upvotes: 0

Views: 642

Answers (2)

The reason you're deleting them one at a time is because you're finding them one at a time. As the other poster mentioned, you could keep track of the locations through out your program (whether that be during this loop), but that wouldn't make it algorithmically efficient (unless you kept track of it somewhere else and pass that info to this method).

I'm not too familiar with using Excel files in Java, but these seems to be a solid way to do it.

Upvotes: 1

Oleksiy
Oleksiy

Reputation: 39859

Why do you have a problem with deleting them one at a time? It doesn't seem too inefficient...

Anyway, I'm pretty sure you still have to loop over every cell to see if it contains "POST". If you have a problem specifically with deleting one row at a time, you could save the indices of the rows you want to delete in an array; then use the array to delete the saved rows.

Upvotes: 1

Related Questions