如何获取if特定列的整行具有POI的特定文本

时间:2016-05-05 12:10:05

标签: java apache-poi

我需要在特定列的单元格文本中的任何位置过滤我的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();
}

2 个答案:

答案 0 :(得分:2)

您可以尝试使用List<HSSFRow>将过滤后的行保存为:

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

答案 1 :(得分:1)

您可能希望有两位逻辑,一位用于处理&#34;匹配&#34;行,一个用于匹配。类似的东西:

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匹配,则会打印出行的内容。如果一行有两次,那么它只打印一次