java - 使用 Apache poi 使​​用 java 从 Excel 获取数据

标签 java excel selenium-webdriver apache-poi

我需要通过传递测试用例 ID 从 Excel 中获取测试数据。如果我将测试用例 ID 作为“TC005”传递 - 我需要获取所有列值,例如实验室名称、实验室地址、城市、州、Pincode、收集中心名称、CC 地址、城市、州和 Pincode。

谁能告诉我怎么做吗?

enter image description here

enter image description here

我已经研究过了,但我只能得到一个字段。

package com.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;


public class ReadExcel {
    static int colTestcase;
     static int rowTestcase;
     static int rownumber ;
     static int colnumber;
     static InputStream input = null;
     static HSSFWorkbook workbook;
     static FileInputStream file ;
     static HSSFSheet sheet;
     static Properties prop = new Properties();


     public static boolean openFile(String fileName) {
            try {
                file = new FileInputStream(fileName);
                workbook = new HSSFWorkbook(file);
                return true;
            }
            catch(Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        public static void main(String args[])
    {
        long startTime = System.currentTimeMillis();
        System.out.println("startTime: "+startTime);
        int rowvalue=readTestCase("TC03");
        int columnvalue=readHeader("Service Title");
        String value=getValuefromExcel(rowvalue,columnvalue);
        System.out.println("Row Value: "+rowvalue);
        System.out.println("Col Value: "+columnvalue);
        System.out.println("Text: "+value);
        long endTime = System.currentTimeMillis();
        System.out.println("endTime"+endTime);
        System.out.println("Took "+(endTime - startTime) + " milliseconds");
    }


    public static String getInputData(String Testcase,String header)
    {
        int rowvalue=readTestCase(Testcase);
        int columnvalue=readHeader(header);
        String value = getValuefromExcel(rowvalue, columnvalue);
        return value;
    }

    public static String getValuefromExcel(int row, int col)
    {
        String value =null;
        String field="Wrongvalue";
        if(!(row==-1||col==-1))
        {
            try {
                System.out.println("Entered");
                input = new FileInputStream("src\\com\\config\\config.properties");
                // load a properties file
                prop.load(input);
                openFile(prop.getProperty("excelTestData_FilePath"));
                //Get first sheet from the workbook
                sheet = workbook.getSheet(prop.getProperty("excelTestData_Sheet"));
                HSSFCell cell = null;
                //Update the value of cell
                cell = sheet.getRow(row).getCell(col);
                value = cell.toString();
                file.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
            System.out.println("value Done");
            return value;
        }
        else {
            System.out.println("Given data was wrong");
        }
    return field;
    }

    public static int readTestCase(String Testcase)
    {
    try {
        FileInputStream file = new FileInputStream(new File("C:\\Thyagu\\Workspace\\PMModule\\test-input\\PM_ModuleTestData.xls"));

        //Get the workbook instance for XLS file 
        HSSFWorkbook workbook = new HSSFWorkbook(file);

        //Get first sheet from the workbook
        HSSFSheet sheet = workbook.getSheet("Data");

        int rowNum = sheet.getLastRowNum()+1;
        int colNum = sheet.getRow(0).getLastCellNum();
        for (int i=1; i<rowNum; i++){
            HSSFRow row = sheet.getRow(i);
            int j=0;
                        HSSFCell cell = row.getCell(j);
                        String value = cell.toString();
                                if(value.equalsIgnoreCase(Testcase))
                                {
                                    rowTestcase=row.getRowNum();
                                    colTestcase=cell.getCellNum();
                                    return rowTestcase;
                                }
                            }
        file.close();
    }
    catch(Exception e){
        e.printStackTrace();
    }
    System.out.println("rownumber Done: " +rowTestcase);
    return -1;
    }

    public static int readHeader(String header)
    {
    try {
        FileInputStream file = new FileInputStream(new File("C:\\Thyagu\\Workspace\\PMModule\\test-input\\PM_ModuleTestData.xls"));

        //Get the workbook instance for XLS file 
        HSSFWorkbook workbook = new HSSFWorkbook(file);

        //Get first sheet from the workbook
        HSSFSheet sheet = workbook.getSheet("Data");

        int rowNum = sheet.getLastRowNum()+1;
        int colNum = sheet.getRow(0).getLastCellNum();
        int i=0;
            HSSFRow row = sheet.getRow(i);
            rownumber =row.getRowNum();
               for (int j=0; j<colNum; j++){
                        HSSFCell cell = row.getCell(j);
                        String value = cell.toString();
                                if(value.equalsIgnoreCase(header))
                                {
                                    rownumber=row.getRowNum();
                                    colnumber=cell.getCellNum();
                                    return colnumber;
                                }
                            }
        file.close(); 
    }
    catch(Exception e){
        e.printStackTrace();
    }
    System.out.println("colnumber Done");
    return -1;
    }
}

提前致谢

最佳答案

Thyagu:我提出一个解决方案...首先,您应该创建一个方法来查找具有所需第一个单元格值的行(在您的情况下我想是所需的 TestCaseID)并返回一个 RowObject

public static HSSFRow findRow(String stringToFind){
            //`hswb` is HSSFWorkbook
    HSSFSheet sheet = hswb.getSheetAt(0);
    Iterator <Row> rowItr = sheet.iterator();
    while(rowItr.hasNext()){
        HSSFRow row = (HSSFRow) rowItr.next();
        if(row.getCell(0).toString().equalsIgnoreCase(stringToFind)){
            return row;
        }
    }
  // If no such row found need to handle NullPointerException for that
    return null;
}

一旦你有了正确的RowObject,你就可以从中提取任何非空单元格值,或者可以做任何你想做的事情,就像在本例中我刚刚打印的一样。

    public static void getAllColumnFromRow(HSSFRow RowObject){
    Iterator<Cell> itr = RowObject.iterator();
    HSSFRow headerRow = RowObject.getSheet().getRow(0);
    String cellValue = "";
    String information = "";
    int headerCellCount = 0;
    //to avoid first column
    itr.next();

    while(itr.hasNext()){
        Cell cell = itr.next();
        Cell headerValue = headerRow.getCell(headerCellCount++);
        switch(cell.getCellType()) {
        case HSSFCell.CELL_TYPE_BOOLEAN:
            cellValue = cell.getBooleanCellValue() +"";
            information = information + " " +headerValue+" - "+cellValue+ "; ";
            break;
        case HSSFCell.CELL_TYPE_NUMERIC:
            cellValue = cell.getNumericCellValue() + "";
            information = information + " " +headerValue+" - "+cellValue+ "; ";
            break;
        case HSSFCell.CELL_TYPE_STRING:
            cellValue = cell.getStringCellValue();
            information = information + " " +headerValue+" - "+cellValue+ "; ";
            break;
        case HSSFCell.CELL_TYPE_BLANK:
            break;
        }
    }
    System.out.println(information);
}

如果有可能在任何行的最后一个单元格值中获取空单元格,则需要使用MissingCellPolicy

关于java - 使用 Apache poi 使​​用 java 从 Excel 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23361379/

相关文章:

java - 如何在 Java 9 中创建没有外部库的 XML 文件?

mysql - 像 MySQL 一样在 EXCEL 中连接

c# - 在 selenium/webdriver c# 中循环遍历多个 moveToElement

python - 如何使用 Selenium (Python) 进行 Google 搜索,然后在新选项卡中打开第一页的结果?

java - 为什么我的 euler 1 项目解决方案不起作用?

java - util 方法与在方法中编写相同代码之间的性能差异...?

c# - 如何以编程方式读取扫描的文档或图像

如果单元格包含某个字符串,Excel If 语句求和

excel - 让一个单元格代表一个单元格范围

testing - Selenium:无法点击类和图像