数据驱动框架---如何使用selenium web驱动程序在Excel工作表中读写

时间:2016-08-24 08:42:50

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

这里使用这段代码来读取,我想写出放在同一张表格上......我想根据相关字段的输出结果为每个sys输出写入结果如何读取和写入现有的excel表? 1

如何使用Selenium Web驱动数据将数据写入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;
}

3 个答案:

答案 0 :(得分:0)

使用java在excel文件中读写,你需要api(Apache POI)

读取excel文件的代码:

<!DOCTYPE html>
<html>
<head>  
<script type="text/javascript" 
    src='lib/angular.min.js'></script> 
<script type="text/javascript" src='lib/angular-route.js'>  </script>
<script type="text/javascript" src='app.js'></script>
<script type="text/javascript" src='controllers.js'></script>
<title></title>
</head>
<body ng-app='myApp'>
<div ng-view>

</div>

</body>
</html>


The partial I am using is home.html:

<section ng-controller='MyCtrl'>
{{test}}
<form>
<input type="text" name="test" ng-model='post'>
<input type="submit" name="sub" value="post" ng-click='getdata()'>
</form>
<table ng-repeat='i in list'>
<tr>
<td>{{i.name}}</td>
<td>{{i.job}}</td>
<form>
<input type="text" 
    name="regname" value='{{i.name}}'   \ng-model='{{i.name}}' hidden>
<td><input type="submit" name="sub2" ng-click='register()'></td>
</form>
</tr>
 </table>
</section>

The app is declared in app.js:
(function () {
// body...
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider){
    $routeProvider
    .when('/', {
        templateUrl: 'home.html',
        controller: 'MyCtrl'
    }).when('/home', {
        templateUrl: 'home.html',
        controller: 'MyCtrl'
    })
   })();

The controller code is in controllers.js:
var app = angular.module('myApp');
app.controller('MyCtrl', 
    ['$scope', '$http', function ($scope, $http) {
// body...
$scope.test = 'the test is running';

$scope.getdata = function(){
    var item = $scope.post;
    console.log(item);
    $scope.list = [{'name': 'shem', 'job':'engineer'}, 
        {'name':   'Reinhard', 'job': 'devops'}]
}
$scope.register = function(){
    console.log($scope.regname);
}`enter code here`


}]);

希望这会对你有所帮助

答案 1 :(得分:0)

要写入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();
        }
    }
}

希望这能解决您的问题

答案 2 :(得分:0)

你走了。

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();
        }
    }
}

我希望这能解决你的问题