How to get the whole row for a if specific column has a certain text with POI

我只是一个虾纸丫 提交于 2019-12-06 14:31:19

You could try to use a List<HSSFRow> to save filtered rows as bellow:

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

You probably want to have two bits of logic, one for handling a "matched" row, one for matching. Something like:

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

That will check every cell in the first sheet, and if the text of a cell in a row matches GHH will then print out the row's contents. If a row has that in twice, it'll only print it once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!