如何使用java获取excel文件中具有特定单元格值的所有行?
我试图查找具有相同单元格值(exp value1)的所有行,因此,例如,我希望搜索: 行1单元格1值单元格2值。。。价值1 第2行。。。。。。。。。。。。。。。。。。。。。。。。。价值2 第3行。。。。。。。。。。。。。。。。。。。。。。。。。价值3 第4行。。。。。。。。。。。。。。。。。。。。。。。。。价值1 第1排和第2排 下面的代码只返回具有所需值的第一行,如何改进它以满足我的需要如何使用java获取excel文件中具有特定单元格值的所有行?,java,excel,apache-poi,Java,Excel,Apache Poi,我试图查找具有相同单元格值(exp value1)的所有行,因此,例如,我希望搜索: 行1单元格1值单元格2值。。。价值1 第2行。。。。。。。。。。。。。。。。。。。。。。。。。价值2 第3行。。。。。。。。。。。。。。。。。。。。。。。。。价值3 第4行。。。。。。。。。。。。。。。。。。。。。。。。。价值1 第1排和第2排 下面的代码只返回具有所需值的第一行,如何改进它以满足我的需要 package questbarreader; import org.apache.poi.openxm
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]);
}
}
}
}您需要将行号添加到列表中,而不是返回行号,然后在浏览完所有行后返回列表
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
}
公共静态列表findRows(工作表、字符串内容){
List matchedRows=新建ArrayList();
用于(行:页){
用于(单元格:行){
if(cell.getCellType()==cell.cell\u类型\u字符串){
if(cell.getRichStringCellValue().getString().trim().contains(cellContent)){
//返回row.getRowNum();而不是此。。。
matchedRows.add(row.getRowNum());//将该行添加到匹配列表中
}
}
}
}
return matchedRows;//如果找不到匹配项,则为空
}
之后,您可以迭代所有匹配项的列表