简体   繁体   English

删除包含特定字符串的多个行

[英]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". 我一直在尝试开发一个代码,可以删除包含特定字符串“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? 是否有可能删除包含String POST的所有行?

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". 无论如何,我很确定你仍然需要遍历每个单元格以查看它是否包含“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. 然后使用该数组删除已保存的行。

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. 我不太熟悉在Java中使用Excel文件,但这些似乎是一种可靠的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM