【问题标题】:How to get the whole row for a if specific column has a certain text with POI如果特定列具有带有 POI 的特定文本,如何获取整行
【发布时间】:2016-05-05 12:10:04
【问题描述】:

我需要在我的 Excel 电子表格中过滤特定列中单元格文本中任何位置的单词“GHH”。我已经设法做到这一点,然后我需要返回找到该文本的整行。我不能这样做,因为似乎没有一种方法可以使用 getRowIndex 方法然后显示整行.

这是我的代码:

public static void main(String[] args) throws IOException {
    FileInputStream fis = new FileInputStream(new File("myfile.xls"));
    HSSFWorkbook workBook = new HSSFWorkbook(fis);
    HSSFSheet sheet = workBook.getSheetAt(0);
    Iterator < Row > rows = sheet.rowIterator();
    while (rows.hasNext()) {
        HSSFRow row = (HSSFRow) rows.next();
        Iterator < Cell > cells = row.cellIterator();
        while (cells.hasNext()) {
            HSSFCell cell = (HSSFCell) cells.next();
            if (cell.toString().contains("GHH")) {
                String key = cell.getStringCellValue();
                int RI = cell.getRowIndex();
            }
        }
    }
    workBook.close();
}

【问题讨论】:

    标签: java apache-poi


    【解决方案1】:

    您可以尝试使用List&lt;HSSFRow&gt; 来保存过滤后的行,如下所示:

    List<HSSFRow> filteredRows = new ArrayList<HSSFRow>();
    Iterator<Row> rows= sheet.rowIterator(); 
    while (rows.hasNext ()){
    HSSFRow row = (HSSFRow) rows.next ();  
     Iterator<Cell> cells = row.cellIterator (); 
     while (cells.hasNext ()){
        HSSFCell cell = (HSSFCell) cells.next (); 
        if (cell.toString().contains("GHH")) {
            String key = cell.getStringCellValue();
            int RI=cell.getRowIndex();
            filteredRows.add(row);
            break;
        }
    }
    // then use filteredRows
    

    【讨论】:

      【解决方案2】:

      您可能需要两种逻辑,一种用于处理“匹配”行,一种用于匹配。比如:

      DataFormatter formatter = new DataFormatter();
      
      public void matchingRow(Row row) {
         System.out.println("Row " + (row.getRowNum()+1) + " matched:");
         for (Cell c : row) {
            System.out.println("   " + formatter.formatCellValue(cell));
         }
      }
      public void handleFile(File excel) throws Exception {
         Workbook wb = WorkbookFactory.create(excel);
         Sheet sheet = wb.getSheetAt(0);
         for (Row row : sheet) {
            boolean matched = false;
            for (Cell cell : row) {
               if (matched) continue;
               if (formatter.formatCellValue(cell).contains("GHH")) {
                  matchingRow(row);
                  matched = true;
               }
            }
         }
      }
      

      这将检查第一张表中的每个单元格,如果一行中的单元格文本与GHH 匹配,则将打印出该行的内容。如果一行有两次,它只会打印一次

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-03
        • 2014-12-13
        • 2021-11-27
        相关资源
        最近更新 更多