有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

每次调用函数时,java都会将数据写入excel文件的新行中

每次在SeleniumWebDriver中调用函数时,我都试图将数据写入新行

我已经编写了如下函数

public class ExcelFunctions 
{  


    XSSFSheet sh;

    int i=0;     

public boolean entertestcaseinexcel(String tcnumber, String description, String value) throws IOException
{
    boolean status = true;  

    try
    {

        XSSFRow row = sh.createRow(i);

        row.createCell(0).setCellValue(tcnumber);
        row.createCell(1).setCellValue(description);
        row.createCell(2).setCellValue(value);
        i++;
    }

    catch(Exception e)
    {
        status = false;
    }
    return status;
}

}

我在这里调用上述函数

import Selenium.ExcelFunctions;

public class ExcelWrite {



    public static void main(String[] args) throws IOException 
    {


        ExcelFunctions EF = new ExcelFunctions();

          File file = new File("D:\\Selenium_Training\\SeleniumNewFile.xlsx");
          FileInputStream fis = new FileInputStream(file);

          XSSFWorkbook wb = new XSSFWorkbook(fis);

          XSSFSheet  sh = wb.getSheetAt(0); 

          EF.entertestcaseinexcel("TC001", "Successfully Logged in", "Pass");

          FileOutputStream fout = new FileOutputStream(file);

          wb.write(fout);    

          fout.close();


    }

}

问题是我能够运行脚本,但我无法将任何值写入excel

你能帮忙吗,先谢谢你


共 (1) 个答案

  1. # 1 楼答案

    您已经在EntertTestCaseInCel函数中硬编码了单元格编号值。从方法的调用方获取该值。以下是您可以使用的示例代码-

    public static void writeTestResultToXLSX(File scenarioFile, String testCaseID, int cellNo, resultEnum rEnum) {
    FileInputStream fis;
    try {
    fis = new FileInputStream(scenarioFile);
    
    XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(fis);
    XSSFSheet sheet = workbook.getSheetAt(0);
    int rowNum = Integer.parseInt(testCaseID);
    Row row = sheet.getRow(rowNum);
    row.createCell(cellNo).setCellValue(rEnum.toString());
    fis.close();
    FileOutputStream fos = new FileOutputStream(scenarioFile);
    workbook.write(fos);
    fos.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (EncryptedDocumentException e) {
      e.printStackTrace();
    } catch (InvalidFormatException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
       }
    }
    

    在上面的代码中,scenarioFile是您想要读取的excel文件的名称,cellNo是您想要回写结果的cellNo,rEnum是具有预定义值的Enum——通过和失败。 通过下面的方法,您可以调用此函数-

    ApachePOIMethods.writeTestResultToXLSX(scenarioFile, testCaseID, XLSXresultCell, resultEnum.FAIL);
    

    要确保的一件事是不要硬编码任何东西,完整的代码是大的,所以不能复制粘贴在这里,以保持答案简短,你可以找到完整的脚本here.