【问题标题】:Data Driven Framework -- how to read and write in excel sheet using Selenium WebDriver with java数据驱动框架——如何使用 Selenium WebDriver 和 java 在 excel 表中读写
【发布时间】:2016-08-24 08:42:50
【问题描述】:

在这里,我正在使用此代码进行阅读,并且我想在同一张纸上写出来.......我想根据将输出放在相关字段如何阅读和写现有的excel表? 1

如何使用 Selenium WebDriver 将数据写入 Excel 文件?

@Test(priority=1)
public void Shift() throws Exception {
String dupshiftname=Skadmin.getData(62, 1);
String validshiftname=Skadmin.getData(63, 1);    

driver.findElement(By.linkText("ADMIN")).click();
driver.findElement(By.id("sessionname")).sendKeys(dupshiftname);
if (actualTitle19.contentEquals(expectedTitle19)){
System.out.println("2.Test Passed!-Submitting without shift name alert      displayed as[Shift name is required]");

//这里我希望将上面的输出写在特定单元格的 excel 表上 }

public static String getData(int r, int c) throws EncryptedDocumentException,   InvalidFormatException, IOException
{    
FileInputStream FIS=new FileInputStream("G://workspace//sample pro//src//testData//excel.xlsx");
  Workbook WB=WorkbookFactory.create(FIS);

DataFormatter formatter = new DataFormatter(); //creating formatter using the default locale
Cell cell = WB.getSheet("Sheet1").getRow(r).getCell(c);
String str = formatter.formatCellValue(cell); //Returns the formatted value  of a cell as a String regardless of the cell type.

return str;
}

【问题讨论】:

    标签: java selenium selenium-webdriver data-driven-tests


    【解决方案1】:

    使用java读取和写入excel文件,你需要api(Apache POI)

    读取excel文件的代码:

    public class ReadExcel 
    {
        public static void main(String[] args) 
        {
            try
            {
                FileInputStream file = new FileInputStream(new File("path\\to\\excel\\file.xlsx"));
    
                //Create Workbook instance holding reference to .xlsx file
                XSSFWorkbook workbook = new XSSFWorkbook(file);
    
                //Get first/desired sheet from the workbook
                XSSFSheet sheet = workbook.getSheetAt(0);
    
                //Iterate through each rows one by one
                Iterator<Row> rowIterator = sheet.iterator();
                while (rowIterator.hasNext()) 
                {
                    Row row = rowIterator.next();
                    //For each row, iterate through all the columns
                    Iterator<Cell> cellIterator = row.cellIterator();
    
                    while (cellIterator.hasNext()) 
                    {
                        Cell cell = cellIterator.next();
                        //Check the cell type and format accordingly
                        switch (cell.getCellType()) 
                        {
                            case Cell.CELL_TYPE_NUMERIC:
                                System.out.print(cell.getNumericCellValue() + "t");
                                break;
                            case Cell.CELL_TYPE_STRING:
                                System.out.print(cell.getStringCellValue() + "t");
                                break;
                        }
                    }
                    System.out.println("");
                }
                file.close();
            } 
            catch (Exception e) 
            {
                e.printStackTrace();
            }
        }
    }
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      在 Excel 表格中编写的代码。

      代码:

      public class WriteExcelDemo 
      {
          public static void main(String[] args) 
          {
              //Blank workbook
              XSSFWorkbook workbook = new XSSFWorkbook(); 
      
              //Create a blank sheet
              XSSFSheet sheet = workbook.createSheet("Employee Data");
      
              //This data needs to be written (Object[])
              Map<String, Object[]> data = new TreeMap<String, Object[]>();
              data.put("1", new Object[] {"ID", "NAME", "LASTNAME"});
              data.put("2", new Object[] {1, "Amit", "Shukla"});
              data.put("3", new Object[] {2, "Lokesh", "Gupta"});
              data.put("4", new Object[] {3, "John", "Adwards"});
              data.put("5", new Object[] {4, "Brian", "Schultz"});
      
              //Iterate over data and write to sheet
              Set<String> keyset = data.keySet();
              int rownum = 0;
              for (String key : keyset)
              {
                  Row row = sheet.createRow(rownum++);
                  Object [] objArr = data.get(key);
                  int cellnum = 0;
                  for (Object obj : objArr)
                  {
                     Cell cell = row.createCell(cellnum++);
                     if(obj instanceof String)
                          cell.setCellValue((String)obj);
                      else if(obj instanceof Integer)
                          cell.setCellValue((Integer)obj);
                  }
              }
              try
              {
                  //Write the workbook in file system
                  FileOutputStream out = new FileOutputStream(new File("howtodoinjava_demo.xlsx"));
                  workbook.write(out);
                  out.close();
                  System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");
              } 
              catch (Exception e) 
              {
                  e.printStackTrace();
              }
          }
      }
      

      希望这能解决您的问题

      【讨论】:

      • Rajan 感谢您的帮助,这将创建一个要写入的新文件,我想在同一个(现有)excel 文件上读写
      • 我知道了,我明天一定会把工作代码发给你。现在我无法访问我的笔记本电脑
      • 我觉得你可以自己做
      【解决方案3】:

      给你。

      Code: 
      
      public class ReadWrite {
      
          public static void main(String[] args) {
      
              try {
                  File excel = new File("D://raju.xlsx");
                  FileInputStream fis = new FileInputStream(excel);
                  XSSFWorkbook book = new XSSFWorkbook(fis);
                  XSSFSheet sheet = book.getSheetAt(0);
      
                  Iterator<Row> itr = sheet.iterator();
      
                  // Iterating over Excel file in Java
                  while (itr.hasNext()) {
                      Row row = itr.next();
      
                      // Iterating over each column of Excel file
                      Iterator<Cell> cellIterator = row.cellIterator();
                      while (cellIterator.hasNext()) {
      
                          Cell cell = cellIterator.next();
      
                          switch (cell.getCellType()) {
                          case Cell.CELL_TYPE_STRING:
                              System.out.print(cell.getStringCellValue() + "\t");
                              break;
                          case Cell.CELL_TYPE_NUMERIC:
                              System.out.print(cell.getNumericCellValue() + "\t");
                              break;
                          case Cell.CELL_TYPE_BOOLEAN:
                              System.out.print(cell.getBooleanCellValue() + "\t");
                              break;
                          default:
      
                          }
                      }
                      System.out.println("");
                  }
      
                  // writing data into XLSX file
                  Map<String, Object[]> newData = new HashMap<String, Object[]>();
                  newData.put("1", new Object[] { 1, "DELL", "7K", "Auto",
                          "USD" });
      
      
                  Set<String> newRows = newData.keySet();
                  int rownum = sheet.getLastRowNum();
      
                  for (String key : newRows) {
                      Row row = sheet.createRow(rownum++);
                      Object[] objArr = newData.get(key);
                      int cellnum = 0;
                      for (Object obj : objArr) {
                          Cell cell = row.createCell(cellnum++);
                          if (obj instanceof String) {
                              cell.setCellValue((String) obj);
                          } else if (obj instanceof Boolean) {
                              cell.setCellValue((Boolean) obj);
                          } else if (obj instanceof Date) {
                              cell.setCellValue((Date) obj);
                          } else if (obj instanceof Double) {
                              cell.setCellValue((Double) obj);
                          }
                      }
                  }
      
                  // open an OutputStream to save written data into Excel file
      
                  FileOutputStream os = new FileOutputStream(excel);
                  book.write(os);
                  System.out.println("Writing on Excel file Finished ...");
      
                  // Close workbook, OutputStream and Excel file to prevent leak
                  os.close();
                  book.close();
                  fis.close();
      
              } catch (FileNotFoundException fe) {
                  fe.printStackTrace();
              } catch (IOException ie) {
                  ie.printStackTrace();
              }
          }
      }
      

      希望能解决你的问题

      【讨论】:

      • Rajan,请您将此代码添加到我的代码中的适当位置...我想为每个@Tests 打印 sysoutprntln 结果在 Excel 表中.....
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2014-05-06
      相关资源
      最近更新 更多