java - 如何在写入文件之前关闭selenium java中的excel文件?

标签 java selenium export-to-excel

我有一个 Java Selenium 测试脚本,可以读取和写入 Excel 文件。问题是,如果文件已打开,则无法写入该文件。我希望我的脚本在写入文件之前自动关闭文件,以防用户忘记关闭 Excel 文件。

下面是打开 Excel 文件并从中读取数据的代码,即使文件已经打开,我也可以毫无问题地读取该文件

// prepare excel file       
FileInputStream file = new FileInputStream(new
File(r.CONFIG.getProperty("testCaseFile")));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(6);  
sheetmyWaitVar.until(ExpectedConditions.elementToBeClickable(By.id("ZipCodeEntry"))).sendKeys(sheet.getRow(row).getCell(2).getStringCellValue());

下面是写入 Excel 文件的代码。如果用户在运行脚本之前忘记关闭 Excel 文件,脚本将卡在此处。我正在尝试找到一种方法在此处添加代码,该代码将在执行下面的代码之前关闭文件

//write random first name to the same file
sheet.getRow(row).getCell(4).setCellValue(randomFirstName);
//write test result to the same file
sheet.getRow(row).getCell(25).setCellValue(testResult);
//write confirmation to the same file
sheet.getRow(row).getCell(23).setCellValue(confirmation); //write the confirmation number in the excel file
//write premium to the same file
sheet.getRow(row).getCell(24).setCellValue(premium); //write premium in the excel file
//enter timestamp
sheet.getRow(row).getCell(27).setCellValue(r.timeStamp());
//enter environment
sheet.getRow(row).getCell(26).setCellValue(r.CONFIG.getProperty("environment"));
FileOutputStream outFile =new FileOutputStream(new File(r.CONFIG.getProperty("testCaseFile")));
workbook.write(outFile);
outFile.close(); 

最佳答案

通常文件上的 writeLock 是独占的,因此为了获得它,文件上不应有其他锁(由操作系统处理)。 我认为没有办法以编程方式解决这个问题。

为什么不将内容写入新文件呢?

关于java - 如何在写入文件之前关闭selenium java中的excel文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29709574/

相关文章:

java - 使用并发 HashMap 的同步块(synchronized block)是否正确?

java - 如何从struts2发送数据到javascript函数来绘制图表

在 IE 中运行的 Selenium Webdriver 脚本在 Firefox 中挂起

c# - 从 C# 导出到 Excel 不显示数据库中的第一行

java - Android 除法始终结果为 0

java - 生成没有给定大小的重复子数组的长字节数组

vba - Selenium VBA 测试用例作为函数

java - WebDriverWait + 搜索项目

java - Apache POI 设置 Excel 图表标题

sql-server - 如何以与 SQL Server 中相同的顺序将列从 SQL 导入 Excel?