[英]How to get Specific Cell Value from Excel With Respect To Row And Column Value using Java POI
[英]How to get the whole row for a if specific column has a certain text with 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();
}
您可以嘗試使用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
您可能希望有兩個邏輯位,一個用於處理“匹配的”行,一個用於匹配。 就像是:
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
相匹配,則將打印出該行的內容。 如果一行中有兩次,則只會打印一次
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.