2016-05-05 40 views
1

我需要在特定列中的單元格文本中的任意位置過濾我的excel電子表格中的單詞「GHH」。我設法做到了這一點,然後我需要返回整個行中發現這個文本。我不能這樣做,因爲似乎沒有辦法使用getRowIndex方法,然後顯示整個行。如何獲得特定列的特定列的整行包含特定文本和POI

這裏是我的代碼:

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

回答

1

你可以嘗試使用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然後將打印出該行的內容。如果一行有兩次,它只會打印一次

相關問題