Example usage for org.apache.poi.ss.usermodel Row getCell

List of usage examples for org.apache.poi.ss.usermodel Row getCell

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Row getCell.

Prototype

Cell getCell(int cellnum);

Source Link

Document

Get the cell representing a given column (logical cell) 0-based.

Usage

From source file:com.compassplus.gui.MainForm.java

private void openFile(File file) { //xlsFileChooser.getSelectedFile()
    try {/*from  w w w  .ja va2  s . c om*/
        Proposal proposal = new Proposal(config);
        FileInputStream inp = new FileInputStream(file);
        final Workbook wb = WorkbookFactory.create(inp);
        inp.close();
        Sheet s = wb.getSheet("PCTSettings");
        String proposalString = null;
        if (s != null) {
            Row r = s.getRow(0);
            if (r != null) {
                Cell c = r.getCell(0);
                if (c != null) {
                    proposalString = c.getStringCellValue();
                }
            }
        }
        if (proposalString == null) {
            throw new PCTDataFormatException("Proposal not found");
        }
        proposal.init(CommonUtils.getInstance().getDocumentFromString(proposalString));
        //ProposalForm tmpForm = new ProposalForm(proposal, getFrame());
        addProposalForm(proposal, getFrame(), true);
        //tmpForm.setChanged(false);
        if (proposal.containsDeprecated()) {
            JOptionPane.showMessageDialog(getRoot(),
                    "Selected proposal contains deprecated module(s) or capacity(ies).", "Warning",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    } catch (Exception exception) {
        //exception.printStackTrace();
        if (exception instanceof PCTDataFormatException) {
            Logger.getInstance().error(exception);
        }
        JOptionPane.showMessageDialog(getRoot(), "Can't read proposal from specified file", "Error",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.compomics.cell_coord.parser.impl.XLSFileParser.java

@Override
public Sample parseTrackFile(File trackFile) throws FileParserException {
    List<Track> list = new ArrayList<>();
    // create a new sample object -- watch out to set the relationships!
    Sample sample = new Sample(trackFile.getName());
    try {//from   w w  w.  ja  v  a 2  s .co m
        FileInputStream fileInputStream = new FileInputStream(trackFile);
        Workbook workbook = null;
        // xls extension
        if (trackFile.getName().endsWith("xls")) {
            workbook = new HSSFWorkbook(fileInputStream);
        } else if (trackFile.getName().endsWith("xlsx")) { // xlsx extension
            workbook = new XSSFWorkbook(fileInputStream);
        }
        if (workbook != null) {
            // check that at least one sheet is present
            if (workbook.getNumberOfSheets() > 0) {
                Track currentTrack = null;
                List<TrackSpot> currentTrackPointList = new ArrayList<>();
                Long currentId = 0L;
                Sheet sheet = workbook.getSheetAt(0);
                // iterate through all the rows, starting from the second one to skip the header
                for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
                    // get the row
                    Row row = sheet.getRow(i);
                    // check the track id
                    Long trackid = (long) row.getCell(0).getNumericCellValue();
                    if (!Objects.equals(currentId, trackid)) {
                        currentTrack = new Track();
                        currentTrack.setTrackid(trackid);
                        list.add(currentTrack);
                        currentId = trackid;
                        currentTrackPointList = new ArrayList<>();
                    }
                    // create new Track Spot object
                    Long spotid = (long) row.getCell(1).getNumericCellValue();
                    double x = row.getCell(2).getNumericCellValue();
                    double y = row.getCell(3).getNumericCellValue();
                    double time = row.getCell(4).getNumericCellValue();
                    TrackSpot trackSpot = new TrackSpot(spotid, x, y, time, currentTrack);
                    currentTrackPointList.add(trackSpot);
                    currentTrack.setTrackSpots(currentTrackPointList);
                    currentTrack.setSample(sample);
                }
            } else {
                throw new FileParserException(
                        "It seems an Excel file does not have any sheets!\nPlease check your files!");
            }
        } else {
            throw new FileParserException("The parser did not find a single workbook!\nCheck your files!!");
        }
    } catch (IOException ex) {
        LOG.error(ex.getMessage(), ex);
    } catch (NumberFormatException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new FileParserException(
                "It seems like a line does not contain a number!\nPlease check your files!");
    }
    sample.setTracks(list);
    return sample;
}

From source file:com.consensus.qa.framework.ExcelOperations.java

public String GetSimType(FileNames fileName, SheetName sheetName) throws IOException {
    String filePath = FilePath(fileName);
    String simType = null;//ww  w  . j  a va2  s. c  o m
    try {
        String sheet = sheetName.toString();
        if (sheetName.toString().contains("_")) {
            String[] Name = sheetName.toString().split("_");
            sheet = Name[1];
        }
        SetStatusForSimTypSheets(sheet, fileName);
        fileInput = new FileInputStream(new File(filePath));
        workBook = new XSSFWorkbook(fileInput);
        XSSFSheet workSheet = workBook.getSheet(sheet);
        for (int i = 0; i < workSheet.getPhysicalNumberOfRows(); i++) {
            Row currentRow = workSheet.getRow(i);
            int type = 1;
            Cell cell = currentRow.getCell(1);
            try {
                type = cell.getCellType();
                System.out.println(type);
                System.out.println(workSheet.getRow(i).getCell(1).toString());
                System.out.println(cell.getStringCellValue().toLowerCase());
                if (type == 1 && cell.getStringCellValue().toLowerCase()
                        .equals(Status.UNUSED.toString().toLowerCase())) {
                    cell.setCellValue(Status.INUSE.toString());
                    simType = currentRow.getCell(0).getStringCellValue();
                    break;
                }
            }

            catch (Exception e) {
                if (type != 1) {
                    cell = currentRow.createCell(1);
                    cell.setCellValue(Status.UNUSED.toString());
                }
            }
        }
    } catch (Exception ex) {
        Log.error(ex.toString());
    } finally {
        WriteAndCloseFile(filePath, fileInput, workBook);
    }
    return simType;
}

From source file:com.consensus.qa.framework.ExcelOperations.java

public void SetStatusForSimTypSheets(String sheet, FileNames fileName) throws IOException {
    int statusColumn;
    XSSFSheet workSheet = null;//from   ww w. ja v  a 2s.c om
    String filePath = FilePath(fileName);
    fileInput = new FileInputStream(new File(filePath));
    workBook = GetWorkBook(fileName);
    for (int i = 0; i < workBook.getNumberOfSheets(); i++) {
        if (workBook.getSheetName(i).toLowerCase().contains(sheet.toLowerCase())) {
            workSheet = workBook.getSheetAt(i);
            break;
        }
    }

    try {
        for (int i = 0; i < workSheet.getPhysicalNumberOfRows(); i++) {
            Row statusRow = workSheet.getRow(i);
            for (int ct = 0; ct < statusRow.getPhysicalNumberOfCells(); ct++) {
                System.out.println(statusRow.getCell(ct));
            }
            int numOfCells = statusRow.getPhysicalNumberOfCells();
            if (workSheet.getRow(i).getCell(numOfCells - 1).getStringCellValue().toUpperCase()
                    .contains(Status.STATUS.toString())
                    || workSheet.getRow(0).getCell(numOfCells - 1).getStringCellValue().toUpperCase()
                            .contains(Status.UNUSED.toString())
                    || workSheet.getRow(0).getCell(numOfCells - 1).getStringCellValue().toUpperCase()
                            .contains(Status.INUSE.toString())
                    || workSheet.getRow(0).getCell(numOfCells - 1).getStringCellValue().toUpperCase()
                            .contains(Status.USED.toString())) {
                statusColumn = numOfCells - 1;
            } else {
                statusColumn = numOfCells;
                Cell statusCell = workSheet.getRow(i).createCell(statusColumn);
                statusCell.setCellValue(Status.UNUSED.toString());
                continue;
            }
            System.out.println(statusRow.getCell(statusColumn));
            try {
                if (statusRow.getCell(statusColumn) == null) {

                    Cell cell = row.createCell(statusColumn);
                    cell.setCellValue(Status.UNUSED.toString());
                }
            } catch (Exception ex) {
                row.createCell(statusColumn).setCellValue(Status.UNUSED.toString());
            }
        }
    } catch (Exception ex) {
        Log.error(ex.toString());
    } finally {
        WriteAndCloseFile(filePath, fileInput, workBook);
    }
}

From source file:com.cordys.coe.ac.fileconnector.utils.ExcelRead.java

License:Apache License

/**
 * Read records from Excel file//from ww  w .ja va 2s .  c o m
 *
 * @param vcConfig The validator configuration object.
 * @param bUseTupleOld
 * @param filename Name of the Excel file.
 * @param doc Document conatins the request.
 * @param iResponsenode The record XML structure root node, or zero, if only validation is needed.
 * @param sheetno Sheet index of the Excel file.
 * @param startrow row index from which data to be read.
 * @param endrow   row index upto which data to be read.
 * @param startcolumn column index from which data to be read.
 * @param endcolumn column index upto which data to be read.
 */
public static void readall(ValidatorConfig vcConfig, Boolean bUseTupleOld, String filename, Document doc,
        int iResponsenode, int sheetno, int startrow, int endrow, int startcolumn, int endcolumn)
        throws FileException {

    Workbook book = null;
    Sheet sheet;
    Cell cell;
    Row row;
    FileInputStream fileinp = null;
    String sRecordName = vcConfig.mConfigMap.get("excel").lRecordList.get(0).sRecordName;
    try {
        int iRow, iCol, sheetindex, noofsheets;
        File file = new File(filename);
        fileinp = new FileInputStream(filename);
        if (file.exists()) {
            if (file.getName().substring(file.getName().lastIndexOf(".") + 1).equalsIgnoreCase("xls")) {
                book = (Workbook) new HSSFWorkbook(fileinp);
            } else if (file.getName().substring(file.getName().lastIndexOf(".") + 1).equalsIgnoreCase("xlsx")) {
                book = new XSSFWorkbook(fileinp);
            } else {
                //ERROR
                fileinp.close();
            }
        } else {
            //ERROR
            fileinp.close();
        }

        if (sheetno != -1) {
            sheetindex = sheetno;
            noofsheets = sheetindex + 1;
        } else {
            sheetindex = 0;
            noofsheets = book.getNumberOfSheets();
        }
        for (; sheetindex < noofsheets; sheetindex++) {
            sheet = book.getSheetAt(sheetindex);

            if (endrow == -1) {
                endrow = sheet.getLastRowNum();
                if (startrow == -1) {
                    startrow = 0;
                }
            } else {
                endrow = startrow + endrow - 1;
                if (endrow > sheet.getLastRowNum()) {
                    endrow = sheet.getLastRowNum();
                }
            }

            if (endcolumn == -1) {
                endcolumn = 30;
                if (startcolumn == -1) {
                    startcolumn = 0;
                }
            }
            for (int i = startrow; i <= endrow; i++) {

                row = sheet.getRow(i);

                if (row == null) {
                    int iTup = doc.createElement("tuple", iResponsenode);

                    if (bUseTupleOld) {
                        iTup = doc.createElement("old", iTup);
                    }
                    iRow = doc.createElement(sRecordName, iTup);
                    //Node.setAttribute(iRow, "id", "" + i);
                    ListIterator fieldslist = vcConfig.mConfigMap.get("excel").lRecordList.get(0).lFieldList
                            .listIterator();
                    while (fieldslist.hasNext()) {
                        FieldType excelfields = (FieldType) fieldslist.next();
                        String sColumnName = excelfields.sFieldName;

                        iCol = doc.createTextElement(sColumnName, "", iRow);
                    }
                    continue;
                }
                int iTup = doc.createElement("tuple", iResponsenode);
                if (bUseTupleOld) {
                    iTup = doc.createElement("old", iTup);
                }
                iRow = doc.createElement(sRecordName, iTup);
                ListIterator fieldslist = vcConfig.mConfigMap.get("excel").lRecordList.get(0).lFieldList
                        .listIterator();
                while (fieldslist.hasNext()) {
                    FieldType excelfields = (FieldType) fieldslist.next();
                    int iColumnIndex = Integer.parseInt(excelfields.sColumnIndex);
                    cell = row.getCell(iColumnIndex);
                    String sColumnName = excelfields.sFieldName;
                    if (cell == null) {
                        iCol = doc.createTextElement(sColumnName, "", iRow);
                        continue;
                    }
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_BLANK:
                        iCol = doc.createTextElement(sColumnName, "", iRow);
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        iCol = doc.createTextElement(sColumnName, "" + cell.getBooleanCellValue(), iRow);

                        break;
                    case Cell.CELL_TYPE_ERROR:
                        iCol = doc.createTextElement(sColumnName, "", iRow);
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        iCol = doc.createTextElement(sColumnName, "" + cell.getCellFormula(), iRow);

                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            SimpleDateFormat simpledateformat = new SimpleDateFormat(
                                    "yyyy-MM-dd 'T' HH:mm:ss.S");
                            iCol = doc.createTextElement(sColumnName,
                                    "" + simpledateformat.format(cell.getDateCellValue()), iRow);

                        } else {
                            iCol = doc.createTextElement(sColumnName, "" + cell.getNumericCellValue(), iRow);
                        }
                        break;
                    case Cell.CELL_TYPE_STRING:
                        iCol = doc.createTextElement(sColumnName, "" + cell.getStringCellValue(), iRow);
                        break;
                    default:
                        System.out.println("default");
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
        throw new FileException(e, LogMessages.FILE_NOT_FOUND);
    } catch (IOException e) {
        throw new FileException(e, LogMessages.IOEXCEPTION_WHILE_READING_FILE, filename);
    } finally {
        try {
            fileinp.close();
        } catch (IOException ex) {
            Logger.getLogger(ExcelRead.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.cpjd.roblu.csv.ToCSV.java

License:Apache License

/**
 * Called to convert a row of cells into a line of data that can later be
 * output to the CSV file./* w  w  w. j  a v  a2s. co m*/
 *
 * @param row An instance of either the HSSFRow or XSSFRow classes that
 *            encapsulates information about a row of cells recovered from
 *            an Excel workbook.
 */
private void rowToCSV(Row row) {
    Cell cell;
    int lastCellNum;
    ArrayList<String> csvLine = new ArrayList<>();

    // Check to ensure that a row was recovered from the sheet as it is
    // possible that one or more rows between other populated rows could be
    // missing - blank. If the row does contain cells then...
    if (row != null) {

        // Get the index for the right most cell on the row and then
        // step along the row from left to right recovering the contents
        // of each cell, converting that into a formatted String and
        // then storing the String into the csvLine ArrayList.
        lastCellNum = row.getLastCellNum();
        for (int i = 0; i <= lastCellNum; i++) {
            cell = row.getCell(i);
            if (cell == null) {
                csvLine.add("");
            } else {
                if (cell.getCellType() != 2) {
                    csvLine.add(this.formatter.formatCellValue(cell));
                } else {
                    csvLine.add(this.formatter.formatCellValue(cell, this.evaluator));
                }
            }
        }
        // Make a note of the index number of the right most cell. This value
        // will later be used to ensure that the matrix of data in the CSV file
        // is square.
        if (lastCellNum > this.maxRowWidth) {
            this.maxRowWidth = lastCellNum;
        }
    }
    this.csvData.add(csvLine);
}

From source file:com.crm.webapp.util.ExcelCustomExporter.java

License:Apache License

protected void tableColumnGroup(Sheet sheet, DataTable table, String facetType) {
    ColumnGroup cg = table.getColumnGroup(facetType);
    List<UIComponent> headerComponentList = null;
    if (cg != null) {
        headerComponentList = cg.getChildren();
    }//from www.j av  a2  s . c  om
    if (headerComponentList != null) {
        for (UIComponent component : headerComponentList) {
            if (component instanceof org.primefaces.component.row.Row) {
                org.primefaces.component.row.Row row = (org.primefaces.component.row.Row) component;
                int sheetRowIndex = sheet.getLastRowNum() + 1;
                Row xlRow = sheet.createRow(sheetRowIndex);
                int i = 0;
                for (UIComponent rowComponent : row.getChildren()) {
                    UIColumn column = (UIColumn) rowComponent;
                    String value = null;
                    if (facetType.equalsIgnoreCase("header")) {
                        value = column.getHeaderText();
                    } else {
                        value = column.getFooterText();
                    }
                    int rowSpan = column.getRowspan();
                    int colSpan = column.getColspan();

                    Cell cell = xlRow.getCell(i);

                    if (rowSpan > 1 || colSpan > 1) {
                        if (rowSpan > 1) {
                            cell = xlRow.createCell((short) i);
                            Boolean rowSpanFlag = false;
                            for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
                                CellRangeAddress merged = sheet.getMergedRegion(j);
                                if (merged.isInRange(sheetRowIndex, i)) {
                                    rowSpanFlag = true;
                                }

                            }
                            if (!rowSpanFlag) {
                                cell.setCellValue(value);
                                cell.setCellStyle(facetStyle);
                                sheet.addMergedRegion(new CellRangeAddress(sheetRowIndex, //first row (0-based)
                                        sheetRowIndex + (rowSpan - 1), //last row  (0-based)
                                        i, //first column (0-based)
                                        i //last column  (0-based)
                                ));
                            }
                        }
                        if (colSpan > 1) {
                            cell = xlRow.createCell((short) i);

                            for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
                                CellRangeAddress merged = sheet.getMergedRegion(j);
                                if (merged.isInRange(sheetRowIndex, i)) {
                                    cell = xlRow.createCell((short) ++i);
                                }
                            }
                            cell.setCellValue(value);
                            cell.setCellStyle(facetStyle);
                            sheet.addMergedRegion(new CellRangeAddress(sheetRowIndex, //first row (0-based)
                                    sheetRowIndex, //last row  (0-based)
                                    i, //first column (0-based)
                                    i + (colSpan - 1) //last column  (0-based)
                            ));
                            i = i + colSpan - 1;
                        }
                    } else {
                        cell = xlRow.createCell((short) i);
                        for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
                            CellRangeAddress merged = sheet.getMergedRegion(j);
                            if (merged.isInRange(sheetRowIndex, i)) {
                                cell = xlRow.createCell((short) ++i);
                            }
                        }
                        cell.setCellValue(value);
                        cell.setCellStyle(facetStyle);
                    }

                    i++;
                }
            }

        }

    }
}

From source file:com.crm.webapp.util.ExcelCustomExporter.java

License:Apache License

protected void tableColumnGroup(Sheet sheet, SubTable table, String facetType) {
    ColumnGroup cg = table.getColumnGroup(facetType);
    List<UIComponent> headerComponentList = null;
    if (cg != null) {
        headerComponentList = cg.getChildren();
    }/*from  ww  w .j  av  a 2 s.c  o  m*/
    if (headerComponentList != null) {
        for (UIComponent component : headerComponentList) {
            if (component instanceof org.primefaces.component.row.Row) {
                org.primefaces.component.row.Row row = (org.primefaces.component.row.Row) component;
                int sheetRowIndex = sheet.getLastRowNum() + 1;
                Row xlRow = sheet.createRow(sheetRowIndex);
                int i = 0;
                for (UIComponent rowComponent : row.getChildren()) {
                    UIColumn column = (UIColumn) rowComponent;
                    String value = null;
                    if (facetType.equalsIgnoreCase("header")) {
                        value = column.getHeaderText();
                    } else {
                        value = column.getFooterText();
                    }
                    int rowSpan = column.getRowspan();
                    int colSpan = column.getColspan();

                    Cell cell = xlRow.getCell(i);

                    if (rowSpan > 1 || colSpan > 1) {

                        if (rowSpan > 1) {
                            cell = xlRow.createCell((short) i);
                            Boolean rowSpanFlag = false;
                            for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
                                CellRangeAddress merged = sheet.getMergedRegion(j);
                                if (merged.isInRange(sheetRowIndex, i)) {
                                    rowSpanFlag = true;
                                }

                            }
                            if (!rowSpanFlag) {
                                cell.setCellStyle(cellStyle);
                                cell.setCellValue(value);
                                sheet.addMergedRegion(new CellRangeAddress(sheetRowIndex, //first row (0-based)
                                        sheetRowIndex + rowSpan - 1, //last row  (0-based)
                                        i, //first column (0-based)
                                        i //last column  (0-based)
                                ));
                            }
                        }
                        if (colSpan > 1) {
                            cell = xlRow.createCell((short) i);
                            for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
                                CellRangeAddress merged = sheet.getMergedRegion(j);
                                if (merged.isInRange(sheetRowIndex, i)) {
                                    cell = xlRow.createCell((short) ++i);
                                }
                            }
                            cell.setCellStyle(cellStyle);
                            cell.setCellValue(value);
                            sheet.addMergedRegion(new CellRangeAddress(sheetRowIndex, //first row (0-based)
                                    sheetRowIndex, //last row  (0-based)
                                    i, //first column (0-based)
                                    i + colSpan - 1 //last column  (0-based)
                            ));
                            i = i + colSpan - 1;
                        }
                    } else {
                        cell = xlRow.createCell((short) i);
                        for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
                            CellRangeAddress merged = sheet.getMergedRegion(j);
                            if (merged.isInRange(sheetRowIndex, i)) {
                                cell = xlRow.createCell((short) ++i);
                            }
                        }
                        cell.setCellValue(value);
                        cell.setCellStyle(facetStyle);

                    }
                    i++;
                }
            }

        }
    }

}

From source file:com.cseur.utils.ExcelReader.java

public ArrayList<ArrayList<String>> readToMap() throws IOException {

    FileInputStream file = new FileInputStream(xlsFile);
    //Get the workbook instance for XLS file 
    HSSFWorkbook workbook = new HSSFWorkbook(file);

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

    //get pol pod via1 via2 via3 via4 index in column and saved to array
    ArrayList<Integer> portIndexs = new ArrayList(Arrays.asList(null, null, null, null, null, null, null));
    boolean isTableHeader = true;
    //Iterate through each rows one by one
    Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
        //read file, find the columnindex for required order, and then insert the value to valueArray.
        Row row = rowIterator.next();
        //            //escape empty lines
        Iterator<Cell> cellIterator = row.cellIterator();
        if (isTableHeader) {
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                //set absolute columnIndex in the order of POL, POD, VIA1.2.l.3.4
                switch (cell.getStringCellValue().trim().toUpperCase()) {
                case "POL":
                    portIndexs.set(0, cell.getColumnIndex());
                    break;
                case "POD":
                    portIndexs.set(1, cell.getColumnIndex());
                    break;
                case "VIA1":
                    portIndexs.set(2, cell.getColumnIndex());
                    break;
                case "VIA2":
                    portIndexs.set(3, cell.getColumnIndex());
                    break;
                case "VIA3":
                    portIndexs.set(4, cell.getColumnIndex());
                    break;
                case "VIA4":
                    portIndexs.set(5, cell.getColumnIndex());
                    break;
                //                    case "VIA5":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                //                    case "VIA6":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                //                    case "VIA7":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                //                    case "VIA8":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                //                    case "VIA9":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                //                    case "VIA0":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                }/*  w ww.  j a  v a2 s.  c om*/
                //                    portIndexs.trimToSize();
            }
        }
        if (!isTableHeader) {
            ArrayList<String> valueArrayList = new ArrayList<>();
            for (int i = 0; portIndexs.get(i) != null; i++) {
                if (row.getCell(portIndexs.get(i)) != null
                        && !row.getCell(portIndexs.get(i)).getStringCellValue().isEmpty()) {
                    valueArrayList
                            .add(row.getCell(portIndexs.get(i)).getStringCellValue().trim().toUpperCase());
                }
            }
            System.out.println(valueArrayList.size());
            valueArrayList_X.add(valueArrayList);
            //reference added to arraylist. clear the valueArrayList remove the values in valueArrayList_X Too!!
            //valueArrayList.clear();
        }
        isTableHeader = false;//add contents to vector.
    }
    file.close();
    return valueArrayList_X;
}

From source file:com.ctb.importdata.ImportSFDataProcessor.java

public static ArrayList<SalesForceLicenseData> readDataFromXLSXFile(String fileName) {
    File sfDataFile = new File(fileName);
    FileInputStream fileInputStream = null;
    ArrayList<SalesForceLicenseData> sfLicenseDataList = null;

    //read the file in to stream
    if (sfDataFile.exists()) {
        //System.out.println("Reading data from .xlsx file started.");
        logger.info("Reading data from .xlsx file : Started :: Timestamp >> "
                + new Date(System.currentTimeMillis()));
        try {/*from  www  .j  a  v  a2s  .c om*/
            fileInputStream = new FileInputStream(sfDataFile);

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

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

            sfLicenseDataList = new ArrayList<SalesForceLicenseData>();
            SalesForceLicenseData sfld = null;

            if (sheet != null) {
                int totalRows = sheet.getPhysicalNumberOfRows();
                //System.out.println("Total no. of physical rows in file = "+ totalRows);
                logger.info("Total no. of physical rows in file = " + totalRows);
                Row headerRow = sheet.getRow(0);
                Cell headerCell;
                Cell dataCell;
                if (headerRow == null) {
                    //System.out.println("No file header content found.") ;
                    logger.info("No file header content found.");
                } else {
                    int totalHeaderColumns = headerRow.getPhysicalNumberOfCells();
                    //System.out.println("Total no. of header cells = "+ totalHeaderColumns);
                    //logger.info("Total no. of header cells = "+ totalHeaderColumns);
                    for (int rowCtr = 1; rowCtr < totalRows; rowCtr++) {
                        //System.out.println("Row No. >> "+rowCtr);
                        Row dataRow = sheet.getRow(rowCtr);
                        if (dataRow != null) {
                            int totalRowColumns = dataRow.getPhysicalNumberOfCells();
                            //System.out.println("Total no. of current data row cells = "+ totalRowColumns);
                            //logger.info("Total no. of current data row cells = "+ totalRowColumns);
                            logger.info(
                                    "Row No. [" + rowCtr + "] :: Header Column Count = [" + totalHeaderColumns
                                            + "] :: Current Data Row Column Count = [" + totalRowColumns + "]");
                            //Discard dummy rows in spreadsheet if the count of current data row columns not equal to header columns
                            if (totalHeaderColumns == totalRowColumns) {
                                boolean isCustomerIdBlank = dataRow.getCell(0)
                                        .getCellType() == Cell.CELL_TYPE_BLANK ? true : false;
                                boolean isOrgNodeIdBlank = dataRow.getCell(5)
                                        .getCellType() == Cell.CELL_TYPE_BLANK ? true : false;
                                //System.out.println("isCustomerIdBlank >> "+isCustomerIdBlank+" :: isOrgNodeIdBlank >> "+isOrgNodeIdBlank);
                                logger.info("Row No. [" + rowCtr + "] :: isCustomerIdBlank >> "
                                        + isCustomerIdBlank + " :: isOrgNodeIdBlank >> " + isOrgNodeIdBlank);
                                //Condition to skip row for SF data object population if customer id or orgnode id is blank
                                if (!isCustomerIdBlank && !isOrgNodeIdBlank) {
                                    sfld = new SalesForceLicenseData();

                                    // For each row, loop through each column
                                    for (int colCtr = 0; colCtr < totalHeaderColumns; colCtr++) {
                                        //System.out.println("Column No. >> "+colCtr);
                                        headerCell = headerRow.getCell(colCtr);
                                        dataCell = dataRow.getCell(colCtr);
                                        if (dataCell != null) {
                                            //System.out.println("dataCell.getCellType() >> "+dataCell.getCellType());
                                            switch (dataCell.getCellType()) {
                                            case Cell.CELL_TYPE_BOOLEAN:
                                                //Do nothing
                                                System.out.println(dataCell.getBooleanCellValue());
                                                break;

                                            case Cell.CELL_TYPE_NUMERIC:
                                                //System.out.println(dataCell.getNumericCellValue());
                                                populateSFDataNumericColValue(sfld, dataCell, headerCell);
                                                break;

                                            case Cell.CELL_TYPE_STRING:
                                                //System.out.println(dataCell.getStringCellValue());
                                                populateSFDataStrColValue(sfld, dataCell, headerCell);
                                                break;

                                            case Cell.CELL_TYPE_BLANK:
                                                //System.out.println(" ");
                                                populateSFDataBlankColValue(sfld, dataCell, headerCell);
                                                break;

                                            default:
                                                System.out.println(dataCell);
                                                break;
                                            }
                                        }
                                    }

                                    sfLicenseDataList.add(sfld);
                                }
                            }
                        }
                    }

                }
            }

        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException : occurred while procesing :: Filename >> [" + fileName + "]");
            e.printStackTrace(); // unexpected            
        } catch (IOException e) {
            logger.error("IOException : occurred while procesing :: Filename >> [" + fileName + "]");
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException e) {
                logger.error("IOException : occurred while closing file input stream.");
                e.printStackTrace();
            }
        }
        //System.out.println("Reading data from .xlsx file completed.");
        logger.info("Reading data from .xlsx file : Completed :: Timestamp >> "
                + new Date(System.currentTimeMillis()));
    } else {
        //System.out.println("File does not exists");
        logger.error("File does not exists :: Filename >> [" + fileName + "]");
    }
    return sfLicenseDataList;
}