Example usage for org.apache.poi.hssf.usermodel HSSFWorkbook getSheet

List of usage examples for org.apache.poi.hssf.usermodel HSSFWorkbook getSheet

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFWorkbook getSheet.

Prototype


@Override
public HSSFSheet getSheet(String name) 

Source Link

Document

Get sheet with the given name (case insensitive match)

Usage

From source file:org.springframework.web.servlet.view.document.ExcelViewTests.java

License:Apache License

@Test
public void testExcelWithTemplateAndLanguage() throws Exception {
    request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, newDummyLocaleResolver("de", ""));

    AbstractExcelView excelView = new AbstractExcelView() {
        @Override// www .  j  av a 2s .com
        protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook wb,
                HttpServletRequest request, HttpServletResponse response) throws Exception {
            HSSFSheet sheet = wb.getSheet("Sheet1");
            // test all possible permutation of row or column not existing
            HSSFCell cell = getCell(sheet, 2, 4);
            cell.setCellValue("Test Value");
            cell = getCell(sheet, 2, 3);
            setText(cell, "Test Value");
            cell = getCell(sheet, 3, 4);
            setText(cell, "Test Value");
            cell = getCell(sheet, 2, 4);
            setText(cell, "Test Value");
        }
    };

    excelView.setApplicationContext(webAppCtx);
    excelView.setUrl("template");
    excelView.render(new HashMap<String, Object>(), request, response);

    POIFSFileSystem poiFs = new POIFSFileSystem(new ByteArrayInputStream(response.getContentAsByteArray()));
    HSSFWorkbook wb = new HSSFWorkbook(poiFs);
    HSSFSheet sheet = wb.getSheet("Sheet1");
    HSSFRow row = sheet.getRow(0);
    HSSFCell cell = row.getCell(0);
    assertEquals("Test Template auf Deutsch", cell.getStringCellValue());
}

From source file:org.teiid.translator.excel.ExcelExecution.java

License:Open Source License

private Iterator<Row> readXLSFile(File xlsFile) throws TranslatorException {
    try {//from   ww w  .  j av  a  2 s. com
        this.xlsFileStream = new FileInputStream(xlsFile);
        Iterator<Row> rowIter = null;
        String extension = ExcelMetadataProcessor.getFileExtension(xlsFile);
        if (extension.equalsIgnoreCase("xls")) { //$NON-NLS-1$
            HSSFWorkbook workbook = new HSSFWorkbook(this.xlsFileStream);
            HSSFSheet sheet = workbook.getSheet(this.visitor.getSheetName());
            this.evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            rowIter = sheet.iterator();

        } else if (extension.equalsIgnoreCase("xlsx")) { //$NON-NLS-1$
            XSSFWorkbook workbook = new XSSFWorkbook(this.xlsFileStream);
            XSSFSheet sheet = workbook.getSheet(this.visitor.getSheetName());
            this.evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            rowIter = sheet.iterator();
        } else {
            throw new TranslatorException(ExcelPlugin.Event.TEIID23000,
                    ExcelPlugin.Util.gs(ExcelPlugin.Event.TEIID23000));
        }

        // skip up to the first data row
        if (this.visitor.getFirstDataRowNumber() > 0 && rowIter != null) {
            while (rowIter.hasNext()) {
                this.currentRow = rowIter.next();
                if (this.currentRow.getRowNum() >= this.visitor.getFirstDataRowNumber()) {
                    break;
                }
            }
        }
        return rowIter;
    } catch (IOException e) {
        throw new TranslatorException(e);
    }
}

From source file:org.wso2.ws.dataservice.DBUtils.java

License:Apache License

private static OMElement getExcelResult(HSSFWorkbook wb, OMElement queryElement, AxisService axisService)
        throws AxisFault {
    OMElement resultElement = null;// w  ww  .ja v  a 2 s.  c o m

    //OMElement excelElement = queryElement.getFirstChildWithName(new QName("excel"));
    ExcelQuery excelQuery = new ExcelQuery(axisService, queryElement);

    OMElement result = queryElement.getFirstChildWithName(new QName("result"));
    String wrapperElementName = result.getAttributeValue(new QName("element"));
    String rowElementName = result.getAttributeValue(new QName("rowName"));
    String columnDefalut = result.getAttributeValue(new QName("columnDefault"));

    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace(axisService.getTargetNamespace(), "data");
    resultElement = fac.createOMElement(wrapperElementName, omNs);

    if (!axisService.isElementFormDefault()) {
        omNs = fac.createOMNamespace("", "data");
    }

    //Retrieve the sheet name, if user has set it in configuration file
    String sheetName = excelQuery.getWorkBookName();

    //this is used to skip header columns, the spread sheet
    int startReadingFromRow = excelQuery.getStartingRow();
    if (startReadingFromRow >= 0) {
        //rows start from 0
        startReadingFromRow = startReadingFromRow - 1;
    }
    int maxRowCount = excelQuery.getMaxRowCount();

    HSSFSheet sheet = wb.getSheet(sheetName);
    int rowCount = sheet.getPhysicalNumberOfRows();

    //If hasHeaders is set to true, we need first row object in later stage.
    HSSFRow firstRow = null;
    if (excelQuery.hasHeaders()) {
        //assumption : first row is the header row
        firstRow = sheet.getRow(0);
    }

    int processedRowCount = 0;
    for (int r = 0; r < rowCount; r++) {
        if (r >= startReadingFromRow) {
            if (processedRowCount == maxRowCount) {
                break;
            }
            HSSFRow hssfRow = sheet.getRow(r);
            OMElement row = fac.createOMElement(rowElementName, omNs);
            if (rowElementName == null) {
                row = resultElement;
            }

            Iterator elements = result.getChildElements();
            while (elements.hasNext()) {
                OMElement element = (OMElement) elements.next();
                if (element.getLocalName().equals("element")) {
                    String displayTagName = element.getAttributeValue(new QName("name"));
                    String columnValue = element.getAttributeValue(new QName("column"));

                    short a = 1;
                    short columnNumber;
                    if (excelQuery.hasHeaders()) {
                        //if hasHeaders is set to true, column Names should be specified
                        //get the column number using specified name
                        columnNumber = getExcelColumnNumber(columnValue, firstRow);
                    } else {
                        try {
                            columnNumber = (short) (Short.valueOf(columnValue).shortValue() - a);
                        } catch (NumberFormatException e) {
                            log.error("Column value for element : " + displayTagName + " should be a number.",
                                    e);
                            throw new AxisFault(
                                    "Column value for element : " + displayTagName + " should be a number.");
                        }

                    }

                    HSSFCell hssfCell = hssfRow.getCell(columnNumber);
                    String elementValue = "";
                    if (hssfCell != null) {
                        if (HSSFCell.CELL_TYPE_STRING == hssfCell.getCellType()) {
                            elementValue = hssfCell.getRichStringCellValue().getString();
                        } else if (HSSFCell.CELL_TYPE_BLANK == hssfCell.getCellType()) {
                            //do nothing
                        } else if (HSSFCell.CELL_TYPE_BOOLEAN == hssfCell.getCellType()) {
                            elementValue = String.valueOf(hssfCell.getBooleanCellValue());
                        } else if (HSSFCell.CELL_TYPE_FORMULA == hssfCell.getCellType()) {
                            elementValue = "{formula}";
                        } else if (HSSFCell.CELL_TYPE_NUMERIC == hssfCell.getCellType()) {
                            elementValue = String.valueOf(hssfCell.getNumericCellValue());
                        }
                    }

                    if (columnDefalut == null || columnDefalut.equals("element")) {
                        OMElement rowElement = fac.createOMElement(displayTagName, omNs);
                        rowElement.addChild(fac.createOMText(rowElement, elementValue));
                        row.addChild(rowElement);
                    } else if (columnDefalut.equals("attribute")) {
                        row.addAttribute(displayTagName, elementValue, omNs);
                    }
                }
            }
            if (rowElementName != null) {
                resultElement.addChild(row);
                processedRowCount++;
            }
        } //end of if( k >= startReadingFromRow)
    } //for (int r = 0; r < rowCount; r++)
    return resultElement;
}

From source file:rocky.sizecounter.SizeCounterUtil.java

License:Apache License

/**
 * getNmTC.//from   w  w  w.ja  v a 2s .com
 * 
 * @param filePath path of UT file.
 * @return 0
 */
public static int countNmTC(String filePath, String reportSheet, String rowText) {
    FileInputStream fis = null;
    int rowOfReport = 0, nmtc = -1;

    try {
        fis = new FileInputStream(filePath);
        int i = 0;
        if (CommonUtil.getExtension(filePath).equals("xls")) {
            try {
                HSSFWorkbook doc = new HSSFWorkbook(fis);
                HSSFSheet sheet = doc.getSheet(reportSheet);
                for (i = 0; i <= sheet.getLastRowNum(); i++) {
                    if (sheet.getRow(i) == null) {
                        continue;
                    }

                    if (sheet.getRow(i).getCell(2) == null) {
                        continue;
                    }

                    if (sheet.getRow(i).getCell(2).getStringCellValue() == null) {
                        continue;
                    }

                    if (sheet.getRow(i).getCell(2).getStringCellValue().equals(rowText)) {
                        rowOfReport = i;
                    }
                }
                nmtc = (int) sheet.getRow(rowOfReport).getCell(9).getNumericCellValue();
            } catch (Exception e) {
                LOG.warn("Can not count number of UTC in file: " + filePath, e);
            }

        } else if (CommonUtil.getExtension(filePath).equals("xlsx")) {
            try {
                XSSFWorkbook doc = new XSSFWorkbook(fis);
                XSSFSheet sheet = doc.getSheet(reportSheet);
                for (i = 0; i <= sheet.getLastRowNum(); i++) {
                    if (sheet.getRow(i).getCell(2).getStringCellValue().equals(rowText)) {
                        rowOfReport = i;
                    }
                }
                nmtc = (int) sheet.getRow(rowOfReport).getCell(9).getNumericCellValue();
            } catch (Exception e) {
                LOG.warn("Can not count number of UTC in file: " + filePath, e);
            }
        }
    } catch (FileNotFoundException ex) {
        LOG.warn("Invalid when reading file.", ex);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException ex) {
                LOG.warn("Close the file input stream", ex);
            }
        }
    }
    return nmtc;
}

From source file:rocky.sizecounter.SizeCounterUtil.java

License:Apache License

/**
 * Check the input file Path is the UTC or UTR.
 * //from  ww w .jav  a  2s.  c  om
 * @param filePath path of file will be checked
 * @param requiredSheetNames Excel file must contains these sheets
 * @return true if the filePath is UTC or UTR
 * @throws IOException when error reading file
 */
public static boolean isUTCFile(String filePath, String[] requiredSheetNames) {
    try {
        InputStream is = CommonUtil.loadResource(filePath);
        if (CommonUtil.getExtension(filePath).equals("xls")) {
            HSSFWorkbook wb = new HSSFWorkbook(is);

            // Check all required sheets
            for (String sheetName : requiredSheetNames) {
                if (wb.getSheet(sheetName) == null) {
                    return false;
                }
            }
        } else if (CommonUtil.getExtension(filePath).equals("xlsx")) {
            XSSFWorkbook xwb = new XSSFWorkbook(is);
            // Check all required sheets
            for (String sheetName : requiredSheetNames) {
                if (xwb.getSheet(sheetName) == null) {
                    return false;
                }
            }
        }
    } catch (IOException ioEx) {
        LOG.error("Could not check file '" + filePath + "'", ioEx);
        return false;
    }

    return true;
}

From source file:swift.selenium.ExcelUtility.java

License:Open Source License

public static HSSFSheet GetSheet(String FilePath, String SheetName) throws IOException {
    HSSFSheet workSheet = null;// www.  ja  v  a  2 s.c  om
    try {
        InputStream myXls = new FileInputStream(FilePath);
        HSSFWorkbook workBook = new HSSFWorkbook(myXls);
        workSheet = workBook.getSheet(SheetName);
    } catch (Exception e) {
        TransactionMapping.pauseFun("File Not Found " + SheetName);
        e.printStackTrace();
        return null;
    }
    return workSheet;
}

From source file:swift.selenium.WebHelper.java

License:Open Source License

public static void GetCellInfo(String FilePath, HSSFRow rowValues, int valuesRowIndex, int valuesRowCount)
        throws IOException // newly Added two Variables for Action Loop
{
    try {//from  w  w  w.  j  a  va 2 s .c o  m
        frmDate = new Date();
        isDynamicNumFound = true;
        List<WebElement> controlList = null;
        //String testCase = null;
        String ctrlValue = null;
        //HSSFRow structureRow=null;
        InputStream myXls = new FileInputStream(FilePath);
        HSSFWorkbook workBook = new HSSFWorkbook(myXls);
        format = workBook.createDataFormat();
        HSSFSheet sheetStructure = workBook.getSheet("Structure");
        //HSSFCell controlValue=null;
        int rowCount = sheetStructure.getLastRowNum() + 1;
        HSSFSheet headerValues = ExcelUtility.GetSheet(FilePath, "Values");
        //HSSFRow headerRow = headerValues.getRow(0);
        System.out.println(Automation.dtFormat.format(frmDate));
        String fromDate = Automation.dtFormat.format(frmDate);
        TransactionMapping.report.setFromDate(fromDate);
        structureHeader = getValueFromHashMap(sheetStructure);
        columnName = null;
        int dynamicIndexNumber;//Added for Action Loop
        String imageType, indexVal, controlName, executeFlag, action, logicalName, controltype, controlID,
                dynamicIndex, newDynamicIndex, rowNo, colNo;//newly Added for Action Loop

        //Setting of default reporting values before executing a transaction
        TransactionMapping.report.setStrMessage("");
        TransactionMapping.report.setStrStatus("PASS");

        for (int rowIndex = 1; rowIndex < rowCount; rowIndex++) {
            //structureRow = sheetStructure.getRow(rowIndex);
            controlName = getCellData("ControlName", sheetStructure, rowIndex, structureHeader);//structureRow.getCell(3);
            executeFlag = getCellData("ExecuteFlag", sheetStructure, rowIndex, structureHeader);//structureRow.getCell(0);

            if (executeFlag.toString().equals("Y")) {
                WebElement webElement = null;
                imageType = getCellData("ImageType", sheetStructure, rowIndex, structureHeader);
                action = getCellData("Action", sheetStructure, rowIndex, structureHeader);//structureRow.getCell(1);
                logicalName = getCellData("LogicalName", sheetStructure, rowIndex, structureHeader);//structureRow.getCell(2);
                controltype = getCellData("ControlType", sheetStructure, rowIndex, structureHeader);//structureRow.getCell(4);
                controlID = getCellData("ControlID", sheetStructure, rowIndex, structureHeader);//structureRow.getCell(6);
                indexVal = getCellData("Index", sheetStructure, rowIndex, structureHeader);//structureRow.getCell(7);
                columnName = getCellData("ColumnName", sheetStructure, rowIndex, structureHeader);
                rowNo = getCellData("RowNo", sheetStructure, rowIndex, structureHeader);
                colNo = getCellData("ColumnNo", sheetStructure, rowIndex, structureHeader);
                dynamicIndex = getCellData("DynamicIndex", sheetStructure, rowIndex, structureHeader);//Added code for Loop

                if (action.equalsIgnoreCase("LOOP")) {
                    loopRow = rowIndex + 1;
                }

                // if rownum != 1 , then do below steps 
                if ((valuesRowIndex != ExcelUtility.firstRow) && (dynamicIndex.length() > 0)) //valuesRowIndex
                {

                    dynamicIndexNumber = Integer
                            .parseInt(dynamicIndex.substring(dynamicIndex.length() - 1, dynamicIndex.length()));

                    if (ExcelUtility.dynamicNum == 0) {
                        ExcelUtility.dynamicNum = dynamicIndexNumber + 1;
                        isDynamicNumFound = false;

                    } else if (ExcelUtility.dynamicNum != 0 && isDynamicNumFound) {
                        ExcelUtility.dynamicNum = ExcelUtility.dynamicNum + 1;
                        isDynamicNumFound = false;
                    }

                    newDynamicIndex = dynamicIndex.replace(String.valueOf(dynamicIndexNumber),
                            String.valueOf(ExcelUtility.dynamicNum));
                    controlName = controlName.replace(dynamicIndex, newDynamicIndex);
                }

                /**Stop the execution of the current test case unexpected alert**/
                control = controltype.toString();

                if (!action.equalsIgnoreCase("LOOP") && !action.equalsIgnoreCase("END_LOOP")) {
                    //boolean isControlValueFound =false;
                    if (valuesHeader.isEmpty() == true) {
                        valuesHeader = getValueFromHashMap(headerValues);
                    }
                    Object actualValue = null;
                    if (logicalName != null) {
                        actualValue = valuesHeader.get(logicalName.toString());
                    } //headerRow.getCell(colIndex);
                    if (actualValue == null) {
                        System.out.println("Null");
                    } else {
                        //int colIndex = Integer.parseInt(actualValue.toString());
                        //controlValue = rowValues.getCell(colIndex);
                        ctrlValue = getCellData(logicalName, headerValues, valuesRowIndex, valuesHeader);

                        testcaseID = rowValues
                                .getCell(Integer.parseInt(valuesHeader.get("TestCaseID").toString()));

                        if (testcaseID == null) {
                            testCase = "";
                        } else {
                            testCase = testcaseID.toString();
                        }
                        transactionType = rowValues
                                .getCell(Integer.parseInt(valuesHeader.get("TransactionType").toString()));
                    }

                    if ((action.equals("I") && !ctrlValue.isEmpty())
                            || (action.equals("V") && !ctrlValue.isEmpty()) || !action.equals("I")) {
                        if (!controltype.startsWith("Sikuli")) {
                            if (!action.equalsIgnoreCase("LOOP") && !controltype.equalsIgnoreCase("Wait")
                                    && !action.equalsIgnoreCase("END_LOOP")
                                    && !controltype.equalsIgnoreCase("Browser")
                                    && !controltype.equalsIgnoreCase("Window")
                                    && !controltype.equalsIgnoreCase("Alert")
                                    && !controltype.equalsIgnoreCase("URL")
                                    && !controltype.equalsIgnoreCase("WaitForJS")
                                    && !controltype.contains("Robot")
                                    && !controltype.equalsIgnoreCase("BrowserType")
                                    && !controltype.equalsIgnoreCase("BrowserAuth")
                                    && !controltype.equalsIgnoreCase("Calendar")
                                    && !controltype.equalsIgnoreCase("CalendarNew")
                                    && !controltype.equalsIgnoreCase("CalendarIPF")
                                    && !controltype.equalsIgnoreCase("CalendarEBP")
                                    && (!action.equalsIgnoreCase("Read")
                                            || ((action.equalsIgnoreCase("Read") && !controlName.isEmpty())))
                                    && !controltype.equalsIgnoreCase("JSScript")
                                    && !controltype.equalsIgnoreCase("DB") && !controlID.equalsIgnoreCase("XML")
                                    && !controltype.startsWith("Process") && !controltype.startsWith("Destroy")
                                    && !controltype.startsWith("ReadSikuli")
                                    && !controltype.equalsIgnoreCase("WebService")
                                    && !controltype.equalsIgnoreCase("WebService_REST")
                                    && !controltype.equalsIgnoreCase("JSONResp")
                                    && !action.equalsIgnoreCase("VA") && !action.equalsIgnoreCase("VA")
                                    && !controltype.equalsIgnoreCase("CaptureScreen")
                                    && !controltype.equalsIgnoreCase("CloseWindow")
                                    && !controlID.equalsIgnoreCase("DonutChart")
                                    && !controlID.equalsIgnoreCase("BarChart") && !action.equalsIgnoreCase("GB")
                                    && !controltype.equalsIgnoreCase("SwitchContext")
                                    && !controltype.equalsIgnoreCase("SwipeDown")) {
                                if ((indexVal.equalsIgnoreCase("") || indexVal.equalsIgnoreCase("0"))
                                        && !controlID.equalsIgnoreCase("TagValue")
                                        && !controlID.equalsIgnoreCase("TagText")) {
                                    webElement = getElementByType(controlID, controlName, control, imageType,
                                            ctrlValue);

                                } else {
                                    controlList = getElementsByType(controlID, controlName, control, imageType,
                                            ctrlValue);

                                    if (controlList != null && controlList.size() > 1) {
                                        webElement = GetControlByIndex(indexVal, controlList, controlID,
                                                controlName, control, ctrlValue); //, ISelenium selenium)
                                    } else {
                                        break;
                                    }
                                }
                            }
                        } else {
                            sikuliScreen = new Screen();
                        }
                    }

                    /***   Perform action on the identified control   ***/
                    doAction(imageType, controltype, controlID, controlName, ctrlValue, logicalName, action,
                            webElement, true, sheetStructure, headerValues, rowIndex, rowCount, rowNo, colNo);
                }

                if (action == "END_LOOP" && (valuesRowCount != valuesRowIndex)) {
                    loopRow = 1;
                    break;
                }

            } else {
                System.out.println("ExecuteFlag is N");
            }
        }

        //Setting of reporting values after execution in case of no exception
        Date toDate = new Date();
        TransactionMapping.report.setFromDate(Automation.dtFormat.format(frmDate));
        TransactionMapping.report.setStrIteration(Automation.configHashMap.get("CYCLENUMBER").toString());
        TransactionMapping.report.setStrTestcaseId(TransactionMapping.testCaseID.toString());
        //TransactionMapping.report.setStrGroupName(MainController.controllerGroupName.toString());
        TransactionMapping.report.setStrTrasactionType(TransactionMapping.transactionType.toString());
        //TransactionMapping.report.setStrTestDescription(MainController.testDesciption);
        TransactionMapping.report.setToDate(Automation.dtFormat.format(toDate));

        //Setting status for field verification failures
        if (fieldVerFailCount > 0) {
            TransactionMapping.report.setStrMessage("Check Detailed Results");
            TransactionMapping.report.setStrStatus("FAIL");
        }
    } catch (Exception e) {
        TransactionMapping.pauseFun(e.getMessage());
    } finally {
        structureHeader.clear();
        valuesHeader.clear();
        ExcelUtility.writeReport(TransactionMapping.report);
        fieldVerFailCount = 0;
    }
}

From source file:swift.selenium.WebHelper.java

License:Open Source License

public static Boolean writeToExcel(String ctrlValue, WebElement webElement, String controlId,
        String controlType, String controlName, String rowNo, String colNo) throws Exception {
    try {/*from   w w  w .ja  va  2  s  . co  m*/
        FileInputStream in = new FileInputStream(Automation.configHashMap.get("TRANSACTION_INFO").toString());
        HSSFWorkbook uniqueWB = new HSSFWorkbook(in);
        HSSFSheet uniqueNumberSheet = uniqueWB.getSheet("DataSheet");
        HashMap<String, Object> uniqueValuesHashMap = getValueFromHashMap(uniqueNumberSheet);
        HSSFRow uniqueRow = null;
        int rowNum = uniqueNumberSheet.getPhysicalNumberOfRows();

        for (int rIndex = 0; rIndex < rowNum; rIndex++) {
            uniqueRow = uniqueNumberSheet.getRow(rIndex);
            String uniqueTestcaseID = getCellData("TestCaseID", uniqueNumberSheet, rIndex, uniqueValuesHashMap);

            if (TransactionMapping.testCaseID.toString().equals(uniqueTestcaseID))//&& MainController.controllerTransactionType.toString().equals(uniqueTransactionType)
            {
                uniqueRow = uniqueNumberSheet.getRow(rIndex);
                break;
            } else if (rIndex == rowNum - 1) {
                uniqueRow = uniqueNumberSheet.createRow(rowNum);
            }
        }

        if (controlType.equalsIgnoreCase("WebTable")) {
            //TM:commented and updated the following 'if' statement
            //if(Integer.valueOf(rowNo).equals(null)||Integer.valueOf(colNo).equals(null))
            if (StringUtils.isBlank(rowNo) || StringUtils.isBlank(colNo)) {
                TransactionMapping.pauseFun("RowNumber or ColumnNumber is Missing");
                return false;
            } else {
                //ctrlValue = Automation.selenium.getTable(controlName+"."+ Integer.parseInt(rowNo) +"." + Integer.parseInt(colNo));
                ctrlValue = Automation.driver
                        .findElement(By.xpath(controlName + "/tr[" + rowNo + "]/td[" + colNo + "]")).getText();
            }
        } else if (controlType.equalsIgnoreCase("ListBox") || controlType.equalsIgnoreCase("WebList")) {
            ctrlValue = new Select(webElement).getFirstSelectedOption().toString();
        }

        else if (controlType.equalsIgnoreCase("DB")) {
            System.out.println(ctrlValue);
        } else {
            ctrlValue = webElement.getText();
        }

        HSSFCell uniqueTestCaseID = uniqueRow
                .createCell(Integer.parseInt(uniqueValuesHashMap.get("TestCaseID").toString()));
        HSSFCell uniqueCell = uniqueRow
                .createCell(Integer.parseInt(uniqueValuesHashMap.get(columnName).toString()));
        uniqueTestCaseID.setCellValue(TransactionMapping.testCaseID.toString());
        uniqueCell.setCellValue(ctrlValue);
        in.close();
        FileOutputStream out = new FileOutputStream(
                Automation.configHashMap.get("TRANSACTION_INFO").toString());
        uniqueWB.write(out);
    } catch (FileNotFoundException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    }
    return true;
}

From source file:SwiftSeleniumWeb.ExcelUtility.java

License:Open Source License

/**
 * Reads Excel-Sheet values by taking Path and SheetName
 * @param FilePath//from ww w  . j  a  va 2 s .c o  m
 * @param SheetName
 * @return
 * @throws IOException
 */
public static HSSFSheet GetSheet(String FilePath, String SheetName) throws IOException {
    HSSFSheet workSheet = null;
    try {
        InputStream myXls = new FileInputStream(FilePath);
        HSSFWorkbook workBook = new HSSFWorkbook(myXls);
        workSheet = workBook.getSheet(SheetName);
    } catch (Exception e) {
        MainController.pauseFun("File Not Found " + SheetName);
        return null;
    }
    return workSheet;
}

From source file:SwiftSeleniumWeb.WebHelper.java

License:Open Source License

public static void GetCellInfo(String FilePath, HSSFRow rowValues, int valuesRowIndex, int valuesRowCount)
        throws IOException // newly Added two Variables for Action Loop
{
    try {/*from   w  ww .j  av  a 2  s  . c  om*/
        frmDate = new Date();
        isDynamicNumFound = true;
        List<WebElement> controlList = null;
        String ctrlValue = null;
        InputStream myXls = new FileInputStream(FilePath);
        HSSFWorkbook workBook = new HSSFWorkbook(myXls);
        format = workBook.createDataFormat();
        HSSFSheet sheetStructure = workBook.getSheet("Structure");
        int rowCount = sheetStructure.getLastRowNum() + 1;
        HSSFSheet headerValues = ExcelUtility.GetSheet(FilePath, "Values");
        System.out.println(Automation.dtFormat.format(frmDate));
        String fromDate = Automation.dtFormat.format(frmDate);
        SwiftSeleniumWeb.WebDriver.report.setFromDate(fromDate);
        structureHeader = getValueFromHashMap(sheetStructure);
        columnName = null;
        int dynamicIndexNumber;//Added for Action Loop
        String imageType, indexVal, controlName, executeFlag, action, logicalName, controltype, controlID,
                dynamicIndex, newDynamicIndex, rowNo, colNo;//newly Added for Action Loop

        //Setting of default reporting values before executing a transaction
        SwiftSeleniumWeb.WebDriver.report.setStrMessage("");
        SwiftSeleniumWeb.WebDriver.report.setStrStatus("PASS");

        for (int rowIndex = 1; rowIndex < rowCount && !MainController.pauseExecution; rowIndex++) {
            controlName = getCellData("ControlName", sheetStructure, rowIndex, structureHeader);
            executeFlag = getCellData("ExecuteFlag", sheetStructure, rowIndex, structureHeader);

            if (executeFlag.toString().equals("Y")) {
                WebElement webElement = null;
                imageType = getCellData("ImageType", sheetStructure, rowIndex, structureHeader);
                action = getCellData("Action", sheetStructure, rowIndex, structureHeader);
                logicalName = getCellData("LogicalName", sheetStructure, rowIndex, structureHeader);
                controltype = getCellData("ControlType", sheetStructure, rowIndex, structureHeader);
                controlID = getCellData("ControlID", sheetStructure, rowIndex, structureHeader);
                indexVal = getCellData("Index", sheetStructure, rowIndex, structureHeader);
                columnName = getCellData("ColumnName", sheetStructure, rowIndex, structureHeader);
                rowNo = getCellData("RowNo", sheetStructure, rowIndex, structureHeader);
                colNo = getCellData("ColumnNo", sheetStructure, rowIndex, structureHeader);
                dynamicIndex = getCellData("DynamicIndex", sheetStructure, rowIndex, structureHeader);

                if (action.equalsIgnoreCase("LOOP")) {
                    loopRow = rowIndex + 1;
                }

                if ((valuesRowIndex != ExcelUtility.firstRow) && (dynamicIndex.length() > 0)) //valuesRowIndex
                {

                    dynamicIndexNumber = Integer
                            .parseInt(dynamicIndex.substring(dynamicIndex.length() - 1, dynamicIndex.length()));

                    if (ExcelUtility.dynamicNum == 0) {
                        ExcelUtility.dynamicNum = dynamicIndexNumber + 1;
                        isDynamicNumFound = false;

                    } else if (ExcelUtility.dynamicNum != 0 && isDynamicNumFound) {
                        ExcelUtility.dynamicNum = ExcelUtility.dynamicNum + 1;
                        isDynamicNumFound = false;
                    }

                    newDynamicIndex = dynamicIndex.replace(String.valueOf(dynamicIndexNumber),
                            String.valueOf(ExcelUtility.dynamicNum));
                    controlName = controlName.replace(dynamicIndex, newDynamicIndex);
                }

                /**Stop the execution of the current test case unexpected alert**/
                control = controltype.toString();
                if (isAlertPresent(control) == true) {
                    break;
                }

                if (!action.equalsIgnoreCase("LOOP") && !action.equalsIgnoreCase("END_LOOP")) {
                    if (valuesHeader.isEmpty() == true) {
                        valuesHeader = getValueFromHashMap(headerValues);
                    }
                    Object actualValue = null;
                    if (logicalName != null) {
                        actualValue = valuesHeader.get(logicalName.toString());
                    } //headerRow.getCell(colIndex);
                    if (actualValue == null) {
                        System.out.println("Null");
                    } else {
                        ctrlValue = getCellData(logicalName, headerValues, valuesRowIndex, valuesHeader);

                        testcaseID = rowValues
                                .getCell(Integer.parseInt(valuesHeader.get("TestCaseID").toString()));

                        if (testcaseID == null) {
                            testCase = "";
                        } else {
                            testCase = testcaseID.toString();
                        }
                        transactionType = rowValues
                                .getCell(Integer.parseInt(valuesHeader.get("TransactionType").toString()));
                    }

                    if ((action.equals("I") && !ctrlValue.isEmpty())
                            || (action.equals("V") && !ctrlValue.isEmpty()) || !action.equals("I")) {
                        if (!controltype.startsWith("Sikuli")) {
                            if (!action.equalsIgnoreCase("LOOP") && !controltype.equalsIgnoreCase("Wait")
                                    && !action.equalsIgnoreCase("END_LOOP")
                                    && !controltype.equalsIgnoreCase("Browser")
                                    && !controltype.equalsIgnoreCase("Window")
                                    && !controltype.equalsIgnoreCase("Alert")
                                    && !controltype.equalsIgnoreCase("URL")
                                    && !controltype.equalsIgnoreCase("WaitForJS")
                                    && !controltype.contains("Robot")
                                    && !controltype.equalsIgnoreCase("Calendar")
                                    && !controltype.equalsIgnoreCase("CalendarNew")
                                    && !controltype.equalsIgnoreCase("CalendarIPF")
                                    && !controltype.equalsIgnoreCase("CalendarEBP")
                                    && (!action.equalsIgnoreCase("Read")
                                            || ((action.equalsIgnoreCase("Read") && !controlName.isEmpty())))
                                    && !controltype.equalsIgnoreCase("JSScript")
                                    && !controltype.equalsIgnoreCase("DB") && !controlID.equalsIgnoreCase("XML")
                                    && !controltype.startsWith("Process") && !controltype.startsWith("Destroy")
                                    && !controltype.startsWith("ReadSikuli")
                                    && !controltype.equalsIgnoreCase("WebService")) {
                                if ((indexVal.equalsIgnoreCase("") || indexVal.equalsIgnoreCase("0"))
                                        && !controlID.equalsIgnoreCase("TagValue")
                                        && !controlID.equalsIgnoreCase("TagText")) {
                                    webElement = getElementByType(controlID, controlName, control, imageType,
                                            ctrlValue);

                                } else {
                                    controlList = getElementsByType(controlID, controlName, control, imageType,
                                            ctrlValue);

                                    if (controlList != null && controlList.size() > 1) {
                                        webElement = GetControlByIndex(indexVal, controlList, controlID,
                                                controlName, control, ctrlValue); //, ISelenium selenium)
                                    } else {
                                        break;
                                    }
                                }
                            }
                        } else {
                            sikuliScreen = new Screen();
                        }
                    }

                    /***   Perform action on the identified control   ***/
                    doAction(imageType, controltype, controlID, controlName, ctrlValue, logicalName, action,
                            webElement, true, sheetStructure, headerValues, rowIndex, rowCount, rowNo, colNo);
                }

                if (action == "END_LOOP" && (valuesRowCount != valuesRowIndex)) {
                    loopRow = 1;
                    break;
                }

            } else {
                System.out.println("ExecuteFlag is N");
            }
        }

        //Setting of reporting values after execution in case of no exception
        Date toDate = new Date();
        SwiftSeleniumWeb.WebDriver.report.setFromDate(Automation.dtFormat.format(frmDate));
        SwiftSeleniumWeb.WebDriver.report
                .setStrIteration(Automation.configHashMap.get("CYCLENUMBER").toString());
        SwiftSeleniumWeb.WebDriver.report.setStrTestcaseId(MainController.controllerTestCaseID.toString());
        SwiftSeleniumWeb.WebDriver.report.setStrGroupName(MainController.controllerGroupName.toString());
        SwiftSeleniumWeb.WebDriver.report
                .setStrTrasactionType(MainController.controllerTransactionType.toString());
        SwiftSeleniumWeb.WebDriver.report.setStrTestDescription(MainController.testDesciption);
        SwiftSeleniumWeb.WebDriver.report.setToDate(Automation.dtFormat.format(toDate));

        //Setting status for field verification failures
        if (fieldVerFailCount > 0) {
            SwiftSeleniumWeb.WebDriver.report.setStrMessage("Check Detailed Results");
            SwiftSeleniumWeb.WebDriver.report.setStrStatus("FAIL");
        }
    } catch (Exception e) {
        MainController.pauseFun(e.getMessage());
    } finally {
        structureHeader.clear();
        valuesHeader.clear();
        ExcelUtility.writeReport(SwiftSeleniumWeb.WebDriver.report);
        fieldVerFailCount = 0;
    }
}