每次调用函数时,将数据写入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。

能否请您提前帮忙,谢谢。

您已经在entertestcaseinexcel函数中硬编码了单元格数值。 从你方法的调用者那里获取这个值。 下面是你可以使用的示例代码 –

 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是具有预定义值的枚举 – PASS和FAIL。 在下面的方式,你可以调用这个函数 –

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

有一点可以肯定的是不要硬编码任何东西,完整的代码很大,所以不能在这里复制粘贴,以保持答案短,你可以在这里find完整的脚本。