如果特定列具有带有 POI 的特定文本,如何获取整行

问题描述 投票:0回答:2

我需要在 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
2个回答
3
投票

您可以尝试使用

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
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.