如何使用java获取具有某个excel文件单元格值的所有行?

时间:2018-04-12 12:21:56

标签: java excel apache-poi

我正在尝试查找具有相同单元格值(exp value1)的所有行,因此例如我想搜索: row1 cell1value cell2value ... value1 row2 ......................... value2 row3 ......................... value3 row4 ......................... value1

并获取row1和row2

下面的代码只返回具有所需值的第一行,如何改进它以完成我需要的操作?

package questbarreader;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;

public class QuestBarReader {
public static String folder = "D:\\Test";
public static String extension = "";
//THIS is the method i use to get row that has specific cell value
public static int findRow(Sheet sheet, String cellContent) {
for (Row row : sheet) {
    for (Cell cell : row) {
        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            if(cell.getRichStringCellValue().getString().trim().contains(cellContent)) {
                return row.getRowNum();

            }
        }
    }
}               
return 0;
}
public static void main(String[] args) throws IOException, InvalidFormatException {

    Iterator it = FileUtils.iterateFiles(new File(folder), null, false);

    while(it.hasNext()){
        String fileName = ((File) it.next()).getName();
        int i = fileName.lastIndexOf('.');
        if(i>0){extension = fileName.substring(i+1);}
        if((fileName.startsWith("sal"))&& extension.equals("xls")){
            String path = (folder + "\\" + fileName);

            Workbook workbook = WorkbookFactory.create(new File(path));
            Sheet sheet = workbook.getSheetAt(0);
            int totalRows = sheet.getLastRowNum();

            int qUltraEnergy = findRow(sheet, "Q ULTRA ENERGY");
            String qUltraEnergyValue = sheet.getRow(qUltraEnergy).getCell(13).getStringCellValue();
            String delims = "[x]+";
            String[] tokens = qUltraEnergyValue.split(delims);
            double kom = Double.valueOf(tokens[0]);

        }
    }  
}  

}

1 个答案:

答案 0 :(得分:0)

您需要将其添加到List中,然后在完成所有行后返回List,而不是返回行号。

public static List<Integer> findRows(Sheet sheet, String cellContent) {
    List<Integer> matchedRows = new ArrayList<>();
    for (Row row : sheet) {
        for (Cell cell : row) {
            if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                if(cell.getRichStringCellValue().getString().trim().contains(cellContent)) {
                    // return row.getRowNum(); Instead of this...
                    matchedRows.add(row.getRowNum()); // Add the row to the list of matches
                }
            }
        }
    }               
    return matchedRows; // will be empty if no matches are found
}

之后,您可以遍历所有匹配列表。