Чтение пустых ячеек в Excel для среды, управляемой данными селенового веб-драйвера - PullRequest
0 голосов
/ 17 апреля 2020

У меня около 5 записей данных в таблице Excel, в которой одна запись имеет 5 значений, одна запись имеет только 4 значения и одна запись имеет только 2 значения. Мой код не может обрабатывать пустые ячейки. Я получаю dataprovider mismatch exception. Кто-нибудь может мне помочь?

Лист Excel Формат: In this sheet we have a barge in the column which is not a mandatory value so sometimes we leave it blank

Здесь данные под баржей в столбце не являются обязательными, поэтому они будут пустыми для нескольких записей.

Java Код для чтения Excel Лист:

    public static Object[][] getTableArray(String FilePath, String SheetName) throws Exception 
{
    String[][] tabArray = null;
    try
    {
        FileInputStream ExcelFile = new FileInputStream(FilePath);
        ExcelWBook = new XSSFWorkbook(ExcelFile);
        ExcelWSheet = ExcelWBook.getSheet(SheetName);
        int startRow = 1;
        int startCol = 0;
        int ci, cj;
        row = ExcelWSheet.getRow(startRow);
        int totalRows = ExcelWSheet.getLastRowNum();
        int totalCols = row.getLastCellNum();
        tabArray = new String[totalRows][totalCols];
        ci = 0;
        for (int i = startRow; i <= totalRows; i++, ci++)
        {
            cj = 0;
            for (int j = startCol; j < totalCols; j++, cj++) 
            {
                tabArray[ci][cj] = getCellData(i, j);
            }
        }
    }catch (FileNotFoundException e) {
        System.out.println("Could not find the Excel sheet");
        e.printStackTrace();
    }catch (IOException e) {
        System.out.println("Could not read the Excel sheet");
        e.printStackTrace();
    }
    return tabArray;
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
    try {
        Cell = row.getCell(ColNum, org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK);
        Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
        String CellData = Cell.getStringCellValue();
        return CellData;
    } catch (Exception e) {
        System.out.println(e.getMessage());
        throw e;
    }
}

Java Функция для принятия параметров:

@Test(dataProvider = "WelcomeMessage", priority = 2)
public void welcomemsg(String survey,String kw, String name,  String verbiage,  String audiofile, String barge) throws Exception {
    try {
        SurveyBuilderPage sp = PageFactory.initElements(MainConfig.getDriver(), SurveyBuilderPage.class);
        sp.setWelcomeMessage(survey, kw, name, verbiage, audiofile, barge);
    }
    catch (Exception e) {
        e.printStackTrace();
        String stackTrace = new Object(){}.getClass().getEnclosingMethod().getName();
        File screenshotFile = ((TakesScreenshot)MainConfig.getDriver()).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(screenshotFile, new File(userdir+"\\Screenshot"+stackTrace+".png"));
    }
}

Так что здесь я получаю ошибку как: Dataprovider mismatch exception.

Здесь welcomemsg функция ожидает 6 параметров, но 6-й параметр является необязательным. Итак, я получаю dataprovider mismatch exception. Здесь мне нужно обработать этот необязательный параметр.

Любая помощь очень ценится.

Заранее спасибо.

1 Ответ

0 голосов
/ 23 апреля 2020

Очевидно, я получаю NullpointerException в методе getCellData в строке кода Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum), когда одна из строк в электронной таблице, как определено в dataProvider, оставлена ​​пустой.

Не могли бы вы попробовать добавить блок try / catch вокруг вызова Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum) возвращает CellData в виде пробелов / пробелов. Вы можете обрабатывать это соответствующим образом в тестовом классе welcomemsg по желанию.

public static String getCellData(int RowNum, int ColNum) throws Exception {
        String CellData;
        try {
            Cell = row.getCell(ColNum, org.apache.poi.ss.usermodel.Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

            try {
                Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
            } catch (NullPointerException npe) {
                CellData = " ";
            }
            if (Cell == null) {
                CellData = " ";
            } else {
                CellData = Cell.getStringCellValue();
            }
            return CellData;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw e;
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...