Example usage for org.apache.poi.xssf.usermodel XSSFWorkbook getSheetAt

List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook getSheetAt

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFWorkbook getSheetAt.

Prototype

@Override
public XSSFSheet getSheetAt(int index) 

Source Link

Document

Get the XSSFSheet object at the given index.

Usage

From source file:com.photon.phresco.framework.commons.FrameworkUtil.java

License:Apache License

public void addNew(String filePath, String testName, String cellValue[]) throws PhrescoException {
    try {/*from   w w  w . j  a v a  2 s  . c om*/
        //FileInputStream myInput = new FileInputStream(filePath);

        int numCol;
        int cellno = 0;
        CellStyle tryStyle[] = new CellStyle[20];
        String sheetName = testName;
        //String cellValue[] = {"","",testName,success, fail,"","","",total,testCoverage,"","",""};
        Iterator<Row> rowIterator;
        File testDir = new File(filePath);
        StringBuilder sb = new StringBuilder(filePath);
        if (testDir.isDirectory()) {
            FilenameFilter filter = new PhrescoFileFilter("", "xlsx");
            File[] listFiles = testDir.listFiles(filter);
            if (listFiles.length != 0) {
                for (File file1 : listFiles) {
                    if (file1.isFile()) {
                        sb.append(File.separator);
                        sb.append(file1.getName());
                        break;
                    }
                }
                FileInputStream myInput = new FileInputStream(sb.toString());
                OPCPackage opc = OPCPackage.open(myInput);

                XSSFWorkbook myWorkBook = new XSSFWorkbook(opc);
                XSSFSheet mySheet = myWorkBook.getSheetAt(0);
                rowIterator = mySheet.rowIterator();
                numCol = 13;
                Row next;
                for (Cell cell : mySheet.getRow((mySheet.getLastRowNum()) - 2)) {
                    tryStyle[cellno] = cell.getCellStyle();
                    cellno = cellno + 1;
                }
                do {

                    int flag = 0;
                    next = rowIterator.next();
                    if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index")
                            && ((mySheet.getLastRowNum() - next.getRowNum()) < 3)) {
                        for (Cell cell : next) {
                            cell.setCellType(1);
                            if (cell.getStringCellValue().equalsIgnoreCase("total")) {
                                mySheet.shiftRows((mySheet.getLastRowNum() - 1),
                                        (mySheet.getPhysicalNumberOfRows() - 1), 1);
                                flag = 1;
                            }
                            if (flag == 1)
                                break;
                        }
                        if (flag == 1)
                            break;
                    }
                } while (rowIterator.hasNext());

                Row r = null;
                if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index")) {
                    r = mySheet.createRow(next.getRowNum() - 1);

                } else {
                    r = mySheet.createRow(next.getRowNum() + 1);
                }
                for (int i = 0; i < numCol; i++) {
                    Cell cell = r.createCell(i);
                    cell.setCellValue(cellValue[i]);
                    // used only when sheet is 'index'
                    if (i == 2)
                        sheetName = cellValue[i];

                    cell.setCellStyle(tryStyle[i]);
                }
                if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index")) {
                    Sheet fromSheet = myWorkBook.getSheetAt((myWorkBook.getNumberOfSheets() - 1));
                    Sheet toSheet = myWorkBook.createSheet(sheetName);
                    int i = 0;
                    Iterator<Row> copyFrom = fromSheet.rowIterator();
                    Row fromRow, toRow;
                    CellStyle newSheetStyle[] = new CellStyle[20];
                    Integer newSheetType[] = new Integer[100];
                    String newSheetValue[] = new String[100];
                    do {
                        fromRow = copyFrom.next();
                        if (fromRow.getRowNum() == 24) {
                            break;
                        }
                        toRow = toSheet.createRow(i);
                        int numCell = 0;
                        for (Cell cell : fromRow) {
                            Cell newCell = toRow.createCell(numCell);

                            cell.setCellType(1);

                            newSheetStyle[numCell] = cell.getCellStyle();
                            newCell.setCellStyle(newSheetStyle[numCell]);

                            newSheetType[numCell] = cell.getCellType();
                            newCell.setCellType(newSheetType[numCell]);
                            if (fromRow.getCell(0).getStringCellValue().length() != 1
                                    && fromRow.getCell(0).getStringCellValue().length() != 2
                                    && fromRow.getCell(0).getStringCellValue().length() != 3) {
                                newSheetValue[numCell] = cell.getStringCellValue();
                                newCell.setCellValue(newSheetValue[numCell]);
                            }

                            numCell = numCell + 1;
                        }
                        i = i + 1;
                    } while (copyFrom.hasNext());
                }
                // write to file
                FileOutputStream fileOut = new FileOutputStream(sb.toString());
                myWorkBook.write(fileOut);
                myInput.close();
                fileOut.close();
            } else {
                FilenameFilter xlsFilter = new PhrescoFileFilter("", "xls");
                File[] xlsListFiles = testDir.listFiles(xlsFilter);
                if (xlsListFiles.length != 0) {
                    for (File file2 : xlsListFiles) {
                        if (file2.isFile()) {
                            sb.append(File.separator);
                            sb.append(file2.getName());
                            break;
                        }
                    }
                    FileInputStream myInput = new FileInputStream(sb.toString());
                    HSSFWorkbook myWorkBook = new HSSFWorkbook(myInput);

                    HSSFSheet mySheet = myWorkBook.getSheetAt(0);
                    rowIterator = mySheet.rowIterator();
                    numCol = 13;
                    Row next;
                    for (Cell cell : mySheet.getRow((mySheet.getLastRowNum()) - 2)) {
                        tryStyle[cellno] = cell.getCellStyle();
                        cellno = cellno + 1;
                    }
                    do {

                        int flag = 0;
                        next = rowIterator.next();
                        if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index")
                                && ((mySheet.getLastRowNum() - next.getRowNum()) < 3)) {
                            for (Cell cell : next) {
                                cell.setCellType(1);
                                if (cell.getStringCellValue().equalsIgnoreCase("total")) {
                                    mySheet.shiftRows((mySheet.getLastRowNum() - 1),
                                            (mySheet.getPhysicalNumberOfRows() - 1), 1);
                                    flag = 1;
                                }
                                if (flag == 1)
                                    break;
                            }
                            if (flag == 1)
                                break;
                        }
                    } while (rowIterator.hasNext());

                    Row r = null;
                    if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index")) {
                        r = mySheet.createRow(mySheet.getLastRowNum() - 2);
                    } else {
                        r = mySheet.createRow(next.getRowNum() + 1);
                    }
                    for (int i = 0; i < numCol; i++) {
                        Cell cell = r.createCell(i);
                        cell.setCellValue(cellValue[i]);
                        // used only when sheet is 'index'
                        if (i == 2)
                            sheetName = cellValue[i];

                        cell.setCellStyle(tryStyle[i]);
                    }
                    if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index")) {
                        Sheet fromSheet = myWorkBook.getSheetAt((myWorkBook.getNumberOfSheets() - 1));
                        Sheet toSheet = myWorkBook.createSheet(sheetName);
                        int i = 0;
                        Iterator<Row> copyFrom = fromSheet.rowIterator();
                        Row fromRow, toRow;
                        CellStyle newSheetStyle[] = new CellStyle[20];
                        Integer newSheetType[] = new Integer[100];
                        String newSheetValue[] = new String[100];
                        do {
                            fromRow = copyFrom.next();
                            if (fromRow.getRowNum() == 24) {
                                break;
                            }
                            toRow = toSheet.createRow(i);
                            int numCell = 0;
                            for (Cell cell : fromRow) {
                                Cell newCell = toRow.createCell(numCell);

                                cell.setCellType(1);

                                newSheetStyle[numCell] = cell.getCellStyle();
                                newCell.setCellStyle(newSheetStyle[numCell]);

                                newSheetType[numCell] = cell.getCellType();
                                newCell.setCellType(newSheetType[numCell]);
                                if (fromRow.getCell(0).getStringCellValue().length() != 1
                                        && fromRow.getCell(0).getStringCellValue().length() != 2
                                        && fromRow.getCell(0).getStringCellValue().length() != 3) {
                                    newSheetValue[numCell] = cell.getStringCellValue();
                                    newCell.setCellValue(newSheetValue[numCell]);
                                }

                                numCell = numCell + 1;
                                if (numCell == 15) {
                                    break;
                                }
                            }
                            i = i + 1;
                        } while (copyFrom.hasNext());
                    }
                    // write to file
                    FileOutputStream fileOut = new FileOutputStream(sb.toString());
                    myWorkBook.write(fileOut);
                    myInput.close();
                    fileOut.close();
                } else {
                    FilenameFilter odsFilter = new PhrescoFileFilter("", "ods");
                    File[] odsListFiles = testDir.listFiles(odsFilter);
                    for (File file1 : odsListFiles) {
                        if (file1.isFile()) {
                            sb.append(File.separator);
                            sb.append(file1.getName());
                            break;
                        }
                    }
                    File file = new File(sb.toString());
                    addTestSuiteToOds(file, cellValue);
                }
            }
        }
    } catch (Exception e) {
        //         throw new PhrescoException(e);
    }
}

From source file:com.photon.phresco.framework.commons.FrameworkUtil.java

License:Apache License

private void writeTestCasesToXLSX(String testSuiteName, String[] cellValue, String status, int numCol,
        int cellno, CellStyle[] tryStyle, StringBuilder sb) throws PhrescoException {
    Iterator<Row> rowIterator;
    try {/*  www . j  av  a 2 s . c o  m*/
        FileInputStream myInput = new FileInputStream(sb.toString());
        OPCPackage opc = OPCPackage.open(myInput);
        XSSFWorkbook myWorkBook = new XSSFWorkbook(opc);
        int numberOfSheets = myWorkBook.getNumberOfSheets();
        for (int j = 0; j < numberOfSheets; j++) {
            XSSFSheet mySheet = myWorkBook.getSheetAt(j);
            if (mySheet.getSheetName().equals(testSuiteName)) {
                rowIterator = mySheet.rowIterator();
                Row next;
                for (Cell cell : mySheet.getRow((mySheet.getLastRowNum()) - 2)) {
                    tryStyle[cellno] = cell.getCellStyle();
                    cellno = cellno + 1;
                }
                float totalPass = 0;
                float totalFail = 0;
                float totalNotApp = 0;
                float totalBlocked = 0;
                float notExecuted = 0;
                float totalTestCases = 0;
                for (int i = 0; i <= 22; i++) {
                    rowIterator.next();
                }
                do {
                    next = rowIterator.next();
                    if (StringUtils.isNotEmpty(getValue(next.getCell(1)))
                            && !getValue(next.getCell(0)).equalsIgnoreCase("S.NO")) {
                        String value = getValue(next.getCell(11));
                        if (StringUtils.isNotEmpty(value)) {
                            if (value.equalsIgnoreCase("success")) {
                                totalPass = totalPass + 1;
                            } else if (value.equalsIgnoreCase("failure")) {
                                totalFail = totalFail + 1;
                            } else if (value.equalsIgnoreCase("notApplicable")) {
                                totalNotApp = totalNotApp + 1;
                            } else if (value.equalsIgnoreCase("blocked")) {
                                totalBlocked = totalBlocked + 1;
                            }
                        } else {
                            notExecuted = notExecuted + 1;
                        }
                    }
                } while (rowIterator.hasNext());
                //to update the status in the index page 
                if (status.equalsIgnoreCase("success")) {
                    totalPass = totalPass + 1;
                } else if (status.equalsIgnoreCase("failure")) {
                    totalFail = totalFail + 1;
                } else if (status.equalsIgnoreCase("notApplicable")) {
                    totalNotApp = totalNotApp + 1;
                } else if (status.equalsIgnoreCase("blocked")) {
                    totalBlocked = totalBlocked + 1;
                } else {
                    notExecuted = notExecuted + 1;
                }
                totalTestCases = totalPass + totalFail + totalNotApp + totalBlocked + notExecuted;
                XSSFSheet mySheet1 = myWorkBook.getSheetAt(0);
                rowIterator = mySheet1.rowIterator();
                for (int i = 0; i <= 2; i++) {
                    rowIterator.next();
                }
                while (rowIterator.hasNext()) {
                    Row next1 = rowIterator.next();
                    if (StringUtils.isNotEmpty(getValue(next1.getCell(2)))
                            && !getValue(next1.getCell(2)).equalsIgnoreCase("Total")) {
                        TestSuite createObject = createObject(next1);
                        if (createObject.getName().equals(testSuiteName)) {
                            addCalculationsToIndex(totalPass, totalFail, totalNotApp, totalBlocked, notExecuted,
                                    totalTestCases, next1);
                        }
                    }
                }

                Row r = null;
                if (mySheet.getSheetName().equalsIgnoreCase("Index")) {
                    r = mySheet.createRow(next.getRowNum() - 1);

                } else {
                    r = mySheet.createRow(next.getRowNum() + 1);
                }
                for (int i = 0; i < numCol; i++) {
                    Cell cell = r.createCell(i);
                    cell.setCellValue(cellValue[i]);

                    cell.setCellStyle(tryStyle[i]);
                }
                FileOutputStream fileOut = new FileOutputStream(sb.toString());
                myWorkBook.write(fileOut);
                myInput.close();
                fileOut.close();
            }

        }
    } catch (PhrescoException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    } catch (InvalidFormatException e) {
        throw new PhrescoException(e);
    }
}

From source file:com.phucdk.emailsender.utils.ExcelUtils.java

public static String getCellValueAsString(int row, int column, XSSFWorkbook myWorkBook) {
    XSSFSheet mySheet = myWorkBook.getSheetAt(1);
    Cell cell = getCell(row, column, mySheet);
    String strCellValue = "";
    FormulaEvaluator evaluator = myWorkBook.getCreationHelper().createFormulaEvaluator();
    if (cell != null) {
        CellValue cellValue = null;//from  w  w  w .j  a  va  2 s.  c o  m
        try {
            cellValue = evaluator.evaluate(cell);
        } catch (Exception ex) {
            log.error("Error when evaluate cell value", ex);
        }

        if (cellValue != null) {
            switch (cellValue.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                strCellValue = String.valueOf(cellValue.getNumberValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                strCellValue = String.valueOf(cellValue.getBooleanValue());
                break;
            case Cell.CELL_TYPE_STRING:
                strCellValue = String.valueOf(cellValue.getStringValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                //strCellValue = String.valueOf(cellValue.get());
                break;
            }
        }

    }
    return strCellValue;
}

From source file:com.phucdk.emailsender.utils.ExcelUtils.java

public static Object getCellValue(int row, int column, XSSFWorkbook myWorkBook) {
    XSSFSheet mySheet = myWorkBook.getSheetAt(1);
    Cell cell = getCell(row, column, mySheet);
    Object cellValueObject = "";
    FormulaEvaluator evaluator = myWorkBook.getCreationHelper().createFormulaEvaluator();
    if (cell != null) {
        CellValue cellValue = null;/* w  w w  . j a va2  s .  co m*/
        try {
            cellValue = evaluator.evaluate(cell);
        } catch (Exception ex) {
            log.error("Error when evaluate cell value", ex);
        }

        if (cellValue != null) {
            switch (cellValue.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                cellValueObject = cellValue.getNumberValue();
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cellValueObject = cellValue.getBooleanValue();
                break;
            case Cell.CELL_TYPE_STRING:
                cellValueObject = cellValue.getStringValue();
                break;
            case Cell.CELL_TYPE_FORMULA:
                //strCellValue = cellValue.getErrorValue();
                break;
            }
        }

    }
    return cellValueObject;
}

From source file:com.phucdk.emailsender.utils.ExcelUtils.java

private static int getNumberOfRows(XSSFWorkbook myWorkBook) {
    XSSFSheet sheet = myWorkBook.getSheetAt(1);
    return sheet.getPhysicalNumberOfRows();
}

From source file:com.qualogy.qafe.service.DocumentServiceImpl.java

License:Apache License

private DocumentOutput handleExcel2007(DocumentParameter parameter) {
    DocumentOutput out = null;//w w  w . j a  va 2s .c  o m
    String uuid = UUIDHelper.generateUUID();
    try {
        XSSFWorkbook workBook = new XSSFWorkbook(new ByteArrayInputStream(parameter.getData()));
        XSSFSheet sheet = workBook.getSheetAt(0);
        out = handleExcelData(sheet, parameter.isFirstFieldHeader());
    } catch (Exception e) {
        LOG.log(Level.FINE, e.getMessage(), e);
        out = new DocumentOutput();
    }
    out.setUuid(uuid);
    return out;
}

From source file:com.rakhi.selenium.readfromexcel.ReadDataFromExcelFileTest.java

@Test
public void testPreloadNPUHomepageFromGoogleSearch() throws Exception {
    try {//w  w  w .ja v  a  2  s  .  co  m
        FileInputStream file = new FileInputStream(
                new File("/Users/rakhipartani/Downloads/CSS522_Automation_Data.xlsx"));
        //HSSFWorkbook workbook = new HSSFWorkbook(file);
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        //HSSFSheet sheet = workbook.getSheetAt(0);
        XSSFSheet sheet = workbook.getSheetAt(0);

        String heading = sheet.getRow(0).getCell(0).getStringCellValue();

        searchText1 = sheet.getRow(1).getCell(0).getStringCellValue();

        searchText2 = sheet.getRow(2).getCell(0).getStringCellValue();

        System.out.println("Heading is: " + heading);

        System.out.println("Search Text 1 is: " + searchText1);

        System.out.println("Search Text 2 is: " + searchText2);

        file.close();

    } catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    driver.get(baseUrl1); // google.com
    driver.manage().window().maximize(); // max window size
    driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS); // wait until page load

    driver.findElement(By.id("UserName")).clear(); // clear
    driver.findElement(By.id("UserName")).sendKeys(searchText1);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    this.sleep(2);
    driver.findElement(By.id("Password")).clear(); // clear
    driver.findElement(By.id("Password")).sendKeys(searchText2);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    this.sleep(2);
    driver.findElement(By.xpath("/html/body/div/div[2]/fieldset/form/p[2]/input")).click(); // Go

    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    this.sleep(2);

    // go back to NPU Home page
    driver.navigate().back();

    // close all
    Thread.sleep(2);
    driver.quit();

}

From source file:com.read.main.LeerPDF.java

/**
 * @param args the command line arguments
 *///  w ww  . j a  v  a  2 s  . co  m
public static void main(String[] args) throws IOException {
    try {

        FileInputStream file = new FileInputStream(new File("/home/aaron/Escritorio/Example.xlsx"));
        XSSFWorkbook workbook2 = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook2.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();

            System.out.println("Numero de Columnas: " + row.getLastCellNum());

            System.out.println(row.getRowNum());

            if (row.getRowNum() == 0) {
                System.out.println("Fila Cero");
            } else {

                int numColumna = 0;

                while (numColumna < row.getLastCellNum()) {

                    Cell cell = row.getCell(numColumna);

                    try {
                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_BOOLEAN:
                            System.out.print(numColumna + ".- BOOLEAN: ");
                            System.out.print(cell.getBooleanCellValue() + "\t\t");
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(numColumna + ".- NUMERIC: ");
                            System.out.print(cell.getNumericCellValue() + "\t\t");
                            break;
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(numColumna + ".- STRING: ");
                            System.out.print(cell.getStringCellValue() + "\t\t");
                            break;
                        }
                    } catch (Exception e) {
                        System.err.println(e);
                    }
                    ;

                    numColumna++;
                }
            }

            System.out.println("");
        }
        file.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.rknowsys.eapp.DataImportAction.java

/**
 * This method saves uploaded file into the server folder.And stores the
 * file data into the database./*  w w w .j  av a2  s . c  om*/
 * 
 * @param actionRequest
 * @param actionResponse
 * @throws IOException
 */
public void saveDataImport(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException {
    System.out.println("saveDataImport method()..!!!!!!!!!!");
    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    Properties properties = PortalUtil.getPortalProperties();
    String uploadDirectory = properties.getProperty("liferay.home") + "/data/uploadedFiles";
    UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
    byte[] bytes = null;

    try {
        // ==========Saving the uploaded file in server folder with uploaded
        // date and time as file filename prefix.===========

        Date date = new Date();
        SimpleDateFormat sd = new SimpleDateFormat("mm-dd-yyyy");
        String d = sd.format(date);
        System.out.println("uploaded date = " + d);
        File uploadedFile = uploadRequest.getFile("fileName");

        bytes = FileUtil.getBytes(uploadedFile);

        String fileName = uploadRequest.getFileName("fileName");
        File newFile = null;
        File newDirectory = new File(uploadDirectory);
        if (!newDirectory.exists()) {
            System.out.println("directory does not exist");
            Path directoryPath = Paths.get(uploadDirectory);
            Files.createDirectory(directoryPath.getParent());
        }
        newFile = new File(uploadDirectory + "/" + d + Calendar.getInstance().getTimeInMillis() + fileName);

        // ============Creating the New file in server folder===========

        if (!newFile.exists()) {
            System.out.println("file does not exist");
            Path pathToFile = Paths
                    .get(uploadDirectory + "/" + d + Calendar.getInstance().getTimeInMillis() + fileName);
            Files.createFile(pathToFile);

        }
        // =========Reading the uploaded file content and writing the
        // content to newly created file==============
        FileInputStream fileInputStream = new FileInputStream(uploadedFile);

        fileInputStream.read(bytes);
        FileOutputStream fileOutputStream = new FileOutputStream(newFile);
        fileOutputStream.write(bytes, 0, bytes.length);
        fileOutputStream.close();
        fileInputStream.close();

        String filePath = newFile.getAbsolutePath();
        System.out.println("filePath = " + filePath);

        FileInputStream file1 = new FileInputStream(new File(filePath));

        // Reading Excel file Rows and cells content using apache poi api
        // and saving the data in to the database.

        XSSFWorkbook workbook = new XSSFWorkbook(file1); // Create Workbook
        // instance
        // holding
        // reference to
        // .xlsx file

        XSSFSheet sheet = workbook.getSheetAt(0); // Get first/desired sheet
        // from the workbook

        @SuppressWarnings("rawtypes")
        Iterator rows = sheet.rowIterator(); // Iterate through each rows
        // one by one

        while (rows.hasNext()) {

            XSSFRow row = (XSSFRow) rows.next();
            if (row.getRowNum() != 0) {
                EmpPersonalDetails empPersonalDetails = EmpPersonalDetailsLocalServiceUtil
                        .createEmpPersonalDetails(CounterLocalServiceUtil.increment());
                Employee employee = EmployeeLocalServiceUtil
                        .createEmployee(CounterLocalServiceUtil.increment());
                JobTitle jobTitle = JobTitleLocalServiceUtil
                        .createJobTitle(CounterLocalServiceUtil.increment());
                SubUnit subUnit = SubUnitLocalServiceUtil.createSubUnit(CounterLocalServiceUtil.increment());
                EmploymentStatus employmentStatus = EmploymentStatusLocalServiceUtil
                        .createEmploymentStatus(CounterLocalServiceUtil.increment());
                EmpJob empJob = EmpJobLocalServiceUtil.createEmpJob(CounterLocalServiceUtil.increment());
                EmpSupervisor empSupervisor = EmpSupervisorLocalServiceUtil
                        .createEmpSupervisor(CounterLocalServiceUtil.increment());
                @SuppressWarnings("rawtypes")
                Iterator cells = row.cellIterator();

                while (cells.hasNext()) {

                    XSSFCell cell = (XSSFCell) cells.next();
                    if (cell.getColumnIndex() == 0) {
                        empPersonalDetails.setFirstName(cell.toString());
                    }
                    if (cell.getColumnIndex() == 1) {
                        empPersonalDetails.setMiddleName(cell.toString());
                    }
                    if (cell.getColumnIndex() == 2) {
                        empPersonalDetails.setLastName(cell.toString());
                    }
                    if (cell.getColumnIndex() == 3) {
                        empPersonalDetails.setEmployeeNo(cell.getRawValue());
                    }
                    if (cell.getColumnIndex() == 4) {
                        empPersonalDetails.setLicenseNo(cell.getRawValue());
                    }
                    if (cell.getColumnIndex() == 5) {
                        jobTitle.setTitle(cell.toString());
                    }
                    if (cell.getColumnIndex() == 6) {
                        employmentStatus.setEmploymentstatus(cell.toString());
                    }
                    if (cell.getColumnIndex() == 7) {
                        subUnit.setName(cell.toString());
                    }

                }
                employee.setUserId(themeDisplay.getUserId());
                employee.setGroupId(themeDisplay.getCompanyGroupId());
                employee.setCompanyId(themeDisplay.getCompanyId());
                employee.setCreateDate(date);
                employee.setModifiedDate(date);
                employee = EmployeeLocalServiceUtil.addEmployee(employee);

                empPersonalDetails.setUserId(themeDisplay.getUserId());
                empPersonalDetails.setGroupId(themeDisplay.getCompanyGroupId());
                empPersonalDetails.setCompanyId(themeDisplay.getCompanyId());
                empPersonalDetails.setCreateDate(date);
                empPersonalDetails.setModifiedDate(date);
                empPersonalDetails.setEmployeeId(employee.getEmployeeId());
                empPersonalDetails = EmpPersonalDetailsLocalServiceUtil
                        .addEmpPersonalDetails(empPersonalDetails);

                jobTitle.setUserId(themeDisplay.getUserId());
                jobTitle.setGroupId(themeDisplay.getCompanyGroupId());
                jobTitle.setCompanyId(themeDisplay.getCompanyId());
                jobTitle.setCreateDate(date);
                jobTitle.setModifiedDate(date);
                jobTitle = JobTitleLocalServiceUtil.addJobTitle(jobTitle);

                subUnit.setUserId(themeDisplay.getUserId());
                subUnit.setGroupId(themeDisplay.getCompanyGroupId());
                subUnit.setCompanyId(themeDisplay.getCompanyId());
                subUnit.setCreateDate(date);
                subUnit.setModifiedDate(date);
                subUnit = SubUnitLocalServiceUtil.addSubUnit(subUnit);

                employmentStatus.setUserId(themeDisplay.getUserId());
                employmentStatus.setGroupId(themeDisplay.getCompanyGroupId());
                employmentStatus.setCompanyId(themeDisplay.getCompanyId());
                employmentStatus.setCreateDate(date);
                employmentStatus.setModifiedDate(date);
                employmentStatus = EmploymentStatusLocalServiceUtil.addEmploymentStatus(employmentStatus);

                empJob.setJobTitleId(employee.getEmployeeId());
                empJob.setEmploymentStatusId(employmentStatus.getEmploymentStatusId());
                empJob.setSubUnitId(subUnit.getSubUnitId());
                empJob.setUserId(themeDisplay.getUserId());
                empJob.setGroupId(themeDisplay.getCompanyGroupId());
                empJob.setCompanyId(themeDisplay.getCompanyId());
                empJob.setCreateDate(date);
                empJob.setModifiedDate(date);
                empJob.setEmployeeId(employee.getEmployeeId());
                empJob = EmpJobLocalServiceUtil.addEmpJob(empJob);

                empSupervisor.setUserId(themeDisplay.getUserId());
                empSupervisor.setGroupId(themeDisplay.getCompanyGroupId());
                empSupervisor.setCompanyId(themeDisplay.getCompanyId());
                empSupervisor.setCreateDate(date);
                empSupervisor.setModifiedDate(date);
                empSupervisor.setEmployeeId(employee.getEmployeeId());
                empSupervisor.setReporterEmployeeId(empPersonalDetails.getEmployeeId());
                empSupervisor = EmpSupervisorLocalServiceUtil.addEmpSupervisor(empSupervisor);
            }

        }
        file1.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.safeway.app.appcert.util.smoketester.TestCaseReader.java

public List<TestScriptTemplate> readExcel() throws Exception {

    FileInputStream file = new FileInputStream(
            new File("C:\\Users\\nbret00\\Documents\\SeleniumSmokeTest\\TestCases.xlsx"));

    List<TestScriptTemplate> tstList = new ArrayList<TestScriptTemplate>();
    //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();

    List<TestScriptTemplate> TestScriptTemplateList = new ArrayList();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();/*from w  w w.  j  a  v  a2  s  .c  om*/
        //skip until row 5
        if (row.getRowNum() > 4) {

            TestScriptTemplate tscripttemp = new TestScriptTemplate();

            //Cell appcode = row.getCell(0); //this should be the item # on the list
            //System.out.println("application name #: "+itemnum.getStringCellValue());
            tscripttemp.setAppCode(getCellValueStr(row.getCell(1)));
            tscripttemp.setAppURL(getCellValueStr(row.getCell(2)));
            tscripttemp.setAppUserID(getCellValueStr(row.getCell(3)));
            tscripttemp.setAppPassword(getCellValueStr(row.getCell(4)));
            tscripttemp.setHomePageTitle(getCellValueStr(row.getCell(5)));
            tscripttemp.setHomePageElementType(getCellValueStr(row.getCell(6)));
            tscripttemp.setHomePageElement(getCellValueStr(row.getCell(7)));
            tscripttemp.setLevel1URL(getCellValueStr(row.getCell(8)));
            tscripttemp.setLevel1PageTitle(getCellValueStr(row.getCell(9)));
            tscripttemp.setLevel1ElementType(getCellValueStr(row.getCell(10)));
            tscripttemp.setLevel1Element(getCellValueStr(row.getCell(11)));

            TestScriptTemplateList.add(tscripttemp);
            System.out.println("this to string: " + tscripttemp.toString());
        }

    }
    file.close();
    return TestScriptTemplateList;
}