Read Excel, is completed by the data driver Testng

background

Data-driven is very commonly used technique we write automation scripts, and data-driven Testng in common annotations are @DataProvider, but this method must return an Object [] []. Recently students often asked, if an external file as a data source, enabling data-driven. For example, when the data source for Excel, how to read excel complete data drive it? The idea is simple, data read excel, excel as the map data for the first row other behavioral Key value, and returns into the map. The method to acquire the corresponding annotation @DataProvider read excel modulation method, get returned Object [] [], the rest are the same use.
ps. the code is not worth the money, the key is to solve the problem of thinking.

Demo

Man of few words said, directly on the Demo.

1. Prepare Excel data

 
Paste_Image.png
  1. New maven project, and import poi related packages:
  <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>

3. Read Excel data, and returned into the Map.

 /**
     * @param file 读取某个excel文件
     * @return Object
     */
    public Object[][] testData(String file) {
        ArrayList<String> arrkey = new ArrayList<String>();
        Workbook workbook = WorkBookEhi.getWorkbook(file);
        Sheet sheet = workbook.getSheetAt(0);
//        获取总行数
        int rowTotalNum = sheet.getLastRowNum()+1;
//        总列数
        int columns = sheet.getRow(0).getPhysicalNumberOfCells();

        HashMap<String, String> [] [] = Map new new the HashMap [rowTotalNum -. 1] [. 1 ];
         // for all the elements of the array are initialized hashmap 
        IF (rowTotalNum>. 1 ) {
             for ( int I = 0; I <rowTotalNum - . 1; I ++ ) { 
                Map [I] [ 0] = new new the HashMap (); 
            } 
        } the else { 
            log.error ( "test Excel" + file + "no data" ); 
        } 
        // get the first row of column names as a hashmap key value 
        for ( int C = 0; C <Columns; C ++ ) { 
            String CellValueCellUnit.getCellValue = (Sheet, 0 , C); 
            arrkey.add (CellValue); 
        } 
        // iterate over all values added to the cells in the hashmap 
        for ( int R & lt =. 1; R & lt <rowTotalNum; R & lt ++ ) {
             for ( int = 0 C; C <Columns; C ++ ) { 
                String CellValue = CellUnit.getCellValue (Sheet, R & lt, C); 
                Map [R & lt -. 1] [0 ] .put (arrkey.get (C), CellValue); 
            } 
        } 
        return Map; 

    }

 

Of course, there's the GetWorkbook () Method I is encapsulated, the code is as follows:

  /**
     * 创建 workbook
     *
     * @param filePath excel文件路径
     * @return Workbook 对象
     * @throws IOException
     */
    public static Workbook getWorkbook(String filePath) {
        Workbook wb = null;
        try {
            if (filePath.endsWith(".xls")) {
                File file = new File(filePath);
                InputStream is = new FileInputStream(file);
                wb = new new HSSFWorkbook (IS); 
            } the else  IF (filePath.endsWith (. "XLSX") || filePath.endsWith ( "xlsm." )) { 
                WB = new new XSSFWorkbook (filePath); 
            } 
        } the catch (IOException E) { 
            E. printStackTrace (); 
        } 
        return WB; 
    } 
CellUnit.getCellValue () method of packaging as follows: 
  / ** 
     * returns the value sheet through the row and column 
     * 
     * @param sheet sheet name 
     * @param rowNum line number 
     * @param cellNum column number 
     *@return 
     * / 
    public  static String getCellValue (Sheet Sheet, int rowNum, int cellNum) { 
        the Cell Cell = sheet.getRow (rowNum) .getCell (cellNum); 
        String value = CellUnit.getCellValue (Cell);
         return value; 
    } 

    
    CellUnit. getCellValue () method of packaging as follows: 
     / ** 
     * converted into a different type of cell string, and returns 
     * 
     * @param cell cell 
     * @return when a cell value
      * / 

    public  static string getCellValue2 (the cell cell) { 
        string value= "";
        switch (cell.getCellTypeEnum()) {
            case STRING:
                value = String.valueOf(cell.getRichStringCellValue());
                return value;
            case NUMERIC:
                value = String.valueOf(cell.getNumericCellValue());
                return value;
            case BOOLEAN:
                value = String.valueOf(cell.getBooleanCellValue());
                return value;

            case FORMULA:
                value = String.valueOf(cell.getCellFormula());
                return value;

            case ERROR:
                value = String.valueOf(cell.getErrorCellValue());
                return value;
            case BLANK:
                return value;
            default:
                log.warn("未知该单元格类型");
                return value;

        }
    }

 

4.Testng use data

    @DataProvider(name = "testData")
    public Object[][] data() {
        TestCaseExcel testcase = new TestCaseExcel();
        return testcase.testData(file);
    }

    @Test(dataProvider = "testData")
    public void testCase(HashMap<String, String> data) {
        String fileName = data.get("excelName");
        String bpSheetName = data.get("Benefits Package Sheet");
        int bpRowNum = Integer.parseInt(data.get("BP sheet RowNum"));
        String csvSheetName = data.get("Cost Share Variances Sheet");
        int csvRowNum = Integer.parseInt(data.get("CSV Sheet RowNum"));
        String hiosPlanID = data.get("HIOS Plan ID");
        String isPass = data.get("isPass");

Author: blog I have migrated meters Yang
link: https: //www.jianshu.com/p/895e4c118db9
Source: Jane books

Guess you like

Origin www.cnblogs.com/xinxin1994/p/11223401.html