0

我一直在尝试开发一个可以删除包含特定字符串“POST”的多行的代码。我一直在这样做:

 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);
       }
   }

事实上,它一次只删除一行。我可以删除所有包含字符串 POST 的行吗?

4

2 回答 2

1

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.

于 2013-06-21T15:40:18.400 回答
1

您一次删除一个的原因是因为您一次只找到一个。正如另一张海报提到的那样,您可以在整个程序中跟踪位置(无论是在此循环期间),但这不会使其在算法上有效(除非您在其他地方跟踪它并将该信息传递给这个方法)。

我不太熟悉在 Java 中使用 Excel 文件,但这些似乎是一种可靠的方法。

于 2013-06-21T15:50:51.387 回答