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

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

Introduction

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

Prototype

int getPhysicalNumberOfCells();

Source Link

Document

Gets the number of defined cells (NOT number of cells in the actual row!).

Usage

From source file:org.openmrs.module.mksreports.renderer.PatientHistoryExcelTemplateRenderer.java

License:Open Source License

/**
 * Adds in a Row to the given Sheet/*www  . j a va 2  s.  c o  m*/
 */
public Row addRow(Workbook wb, SheetToAdd sheetToAdd, RowToAdd rowToAdd, int rowIndex, ReportData reportData,
        ReportDesign design, Map<String, String> repeatSections) {

    // Create a new row and copy over style attributes from the row to add
    Row newRow = sheetToAdd.getSheet().createRow(rowIndex);
    Row rowToClone = rowToAdd.getRowToClone();
    try {
        CellStyle rowStyle = rowToClone.getRowStyle();
        if (rowStyle != null) {
            newRow.setRowStyle(rowStyle);
        }
    } catch (Exception e) {
        // No idea why this is necessary, but this has thrown IndexOutOfBounds errors getting the rowStyle.  Mysteries of POI
    }
    newRow.setHeight(rowToClone.getHeight());

    // Iterate across all of the cells in the row, and configure all those that need to be added/cloned
    List<CellToAdd> cellsToAdd = new ArrayList<CellToAdd>();

    int totalCells = rowToClone.getPhysicalNumberOfCells();
    int cellsFound = 0;
    for (int cellNum = 0; cellsFound < totalCells; cellNum++) {
        Cell currentCell = rowToClone.getCell(cellNum);
        log.debug("Handling cell: " + currentCell);
        if (currentCell != null) {
            cellsFound++;
        }
        // If we find that the cell that we are on is a repeating cell, then add the appropriate number of cells to clone
        String repeatingColumnProperty = getRepeatingColumnProperty(sheetToAdd.getOriginalSheetNum(), cellNum,
                repeatSections);
        if (repeatingColumnProperty != null) {
            String[] dataSetSpanSplit = repeatingColumnProperty.split(",");
            String dataSetName = dataSetSpanSplit[0];
            DataSet dataSet = getDataSet(reportData, dataSetName, rowToAdd.getReplacementData());
            int numCellsToRepeat = 1;
            if (dataSetSpanSplit.length == 2) {
                numCellsToRepeat = Integer.parseInt(dataSetSpanSplit[1]);
            }
            log.debug("Repeating this cell with dataset: " + dataSet + " and repeat of " + numCellsToRepeat);
            int repeatNum = 0;
            for (DataSetRow dataSetRow : dataSet) {
                repeatNum++;
                for (int i = 0; i < numCellsToRepeat; i++) {
                    Cell cell = (i == 0 ? currentCell : rowToClone.getCell(cellNum + i));
                    if (repeatNum == 1 && cell != null && cell != currentCell) {
                        cellsFound++;
                    }
                    Map<String, Object> newReplacements = getReplacementData(rowToAdd.getReplacementData(),
                            reportData, design, dataSetName, dataSetRow, repeatNum);
                    cellsToAdd.add(new CellToAdd(cell, newReplacements));
                    log.debug("Adding " + cell + " with dataSetRow: " + dataSetRow);
                }
            }
            cellNum += numCellsToRepeat;
        } else {
            cellsToAdd.add(new CellToAdd(currentCell, rowToAdd.getReplacementData()));
            log.debug("Adding " + currentCell);
        }
    }

    // Now, go through all of the collected cells, and add them back in

    String prefix = getExpressionPrefix(design);
    String suffix = getExpressionSuffix(design);

    List<CellRangeAddress> newMergedRegions = new ArrayList<CellRangeAddress>();

    for (int i = 0; i < cellsToAdd.size(); i++) {
        CellToAdd cellToAdd = cellsToAdd.get(i);
        Cell newCell = newRow.createCell(i);
        Cell cellToClone = cellToAdd.getCellToClone();
        if (cellToClone != null) {
            Object contents = ExcelUtil.getCellContents(cellToClone);
            newCell.setCellStyle(cellToClone.getCellStyle());

            int numFormattings = sheetToAdd.getSheet().getSheetConditionalFormatting()
                    .getNumConditionalFormattings();
            for (int n = 0; n < numFormattings; n++) {
                ConditionalFormatting f = sheetToAdd.getSheet().getSheetConditionalFormatting()
                        .getConditionalFormattingAt(n);
                for (CellRangeAddress add : f.getFormattingRanges()) {

                    if (add.getFirstRow() == rowToAdd.getRowToClone().getRowNum()
                            && add.getLastRow() == rowToClone.getRowNum()) {
                        if (add.getFirstColumn() == cellToClone.getColumnIndex()
                                && add.getLastColumn() == cellToClone.getColumnIndex()) {
                            ConditionalFormattingRule[] rules = new ConditionalFormattingRule[f
                                    .getNumberOfRules()];
                            for (int j = 0; j < f.getNumberOfRules(); j++) {
                                rules[j] = f.getRule(j);
                            }
                            CellRangeAddress[] cellRange = new CellRangeAddress[1];
                            cellRange[0] = new CellRangeAddress(rowIndex, rowIndex, i, i);
                            sheetToAdd.getSheet().getSheetConditionalFormatting()
                                    .addConditionalFormatting(cellRange, rules);
                        }
                    }
                }
            }

            int numMergedRegions = sheetToAdd.getSheet().getNumMergedRegions();
            for (int n = 0; n < numMergedRegions; n++) {
                CellRangeAddress add = sheetToAdd.getSheet().getMergedRegion(n);
                int rowNum = rowToClone.getRowNum();
                if (add.getFirstRow() == rowNum && add.getLastRow() == rowNum) {
                    if (add.getFirstColumn() == cellToClone.getColumnIndex()) {
                        newMergedRegions
                                .add(new CellRangeAddress(rowNum, rowNum, i, i + add.getNumberOfCells() - 1));
                    }
                }
            }

            if (ObjectUtil.notNull(contents)) {
                if (contents instanceof String) {
                    contents = EvaluationUtil.evaluateExpression(contents.toString(),
                            cellToAdd.getReplacementData(), prefix, suffix);
                }
                ExcelUtil.setCellContents(newCell, contents);
            }

            ExcelUtil.copyFormula(cellToClone, newCell);
        }
    }

    for (CellRangeAddress mergedRegion : newMergedRegions) {
        sheetToAdd.getSheet().addMergedRegion(mergedRegion);
    }

    return newRow;
}

From source file:org.rakuten.util.XLSUtility.java

License:Open Source License

/**
 * @param file//from   w  w  w. ja  va2  s .  c  om
 * @return map of testData 
 * 
 * This method take file name for test data and convert it into map of testCaseId and Object of testData
 * Excel file is expected to have at-least 3 columns else that row will be skipped, testCase id is supposed 
 * to be unique other wise test data will be overridden
 * This method will return null if file does not exists or if file does not contains any data row
 */
public Map<Integer, TestData> getTestData(String file) {
    Iterator<Row> rows = getSheetData(file);
    DataFormatter fmt = new DataFormatter();
    if (rows == null)
        return null;
    Map<Integer, TestData> testData = new HashMap<>();
    while (rows.hasNext()) {
        Row nextRow = rows.next();
        if (nextRow.getPhysicalNumberOfCells() >= 3) {
            try {
                Cell testCaseId = nextRow.getCell(0, Row.RETURN_BLANK_AS_NULL);
                Cell request = nextRow.getCell(1);
                Cell response = nextRow.getCell(2);
                TestData testData2 = new TestData(request.getStringCellValue(), response.getStringCellValue());
                testData.put(Integer.parseInt(fmt.formatCellValue(testCaseId)), testData2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return testData;
}

From source file:org.sakaiproject.gradebook.gwt.server.ImportExportUtilityImpl.java

License:Educational Community License

private boolean hasTooManyItems(Row row, FileFormat format) {
    String[] cells = new String[row.getPhysicalNumberOfCells()];
    int i = 0;/*ww  w .  j  a va2s  .  c  o  m*/
    for (org.apache.poi.ss.usermodel.Cell cell : row) {
        cells[i++] = cell.getStringCellValue().trim();
    }
    return hasTooManyItems(cells, format);
}

From source file:org.squashtest.tm.service.internal.importer.ExcelTestCaseParserImpl.java

License:Open Source License

private boolean validateRegularRow(Row row) {

    boolean validated;

    int lastCell = row.getLastCellNum();
    int nbCell = row.getPhysicalNumberOfCells();

    if (lessThan2Cells(lastCell, nbCell)) {
        validated = false;/*from  w w w  .  j  av a 2  s  .  com*/
    } else {
        validated = checkCellsContent(row);
    }

    return validated;
}

From source file:org.squashtest.tm.service.internal.importer.ExcelTestCaseParserImpl.java

License:Open Source License

private boolean validateStepRow(Row row) {

    boolean validated;

    int lastCell = row.getLastCellNum();
    int nbCell = row.getPhysicalNumberOfCells();

    String text1 = row.getCell(0) != null ? row.getCell(0).getStringCellValue() : "";
    String text2 = "";
    Cell cell2 = row.getCell(1);/*ww  w.ja  va  2 s .  co  m*/

    if (cell2 != null && Cell.CELL_TYPE_STRING == cell2.getCellType()) {
        text2 = cell2.getStringCellValue();
    } else {
        LOGGER.debug("validateStepRow : Cell 1 of row {} was not of string type, empty string will be used",
                row);
    }

    validated = text1.equals(ACTION_STEP_TAG) && !text2.isEmpty() && lastCell >= 3 && nbCell >= 3;

    return validated;

}

From source file:pruebaimportarexcel.excel.Excel.java

/**
 * Devuelve el numero de filas que contiene la pagina actual.
 * //from   ww  w. j  av  a2 s  . c  om
 * @param row
 * @return 
 */
public static int getNumCells(Row row) {
    return (row != null) ? row.getPhysicalNumberOfCells() : 0;
}

From source file:pruebaimportarexcel.excel.Excels.java

/**
 * Devuelve la fila indicada por rowIndex, de la pagina sheet. Si cellSize
 * es 0 o menor optenemos todas las celdas de la fila, si es mayor se
 * optiene el numero indicado./*from w  w  w .ja v a2s . co  m*/
 *
 * @param sheet
 * @param rowIndex
 * @param cellSize
 * @return
 */
public static List<Object> getRowToList(Sheet sheet, int rowIndex, int cellSize) {
    List<Object> resultado = null;
    Row row = null;
    Cell cell = null;
    int numColumns = 0;
    // 1.- Comprobar si existe la pagina y el numero de fila pedido es >= 0;
    if (sheet != null && rowIndex >= 0) {
        row = Excel.getRow(sheet, rowIndex); // Obtener la fila indicada por el rowIndex.

        // 2.- Existe la fila??
        if (row != null) {
            resultado = new ArrayList<>();//Ahora podemos crear un ArrayList con el contenido de la fila.

            numColumns = (cellSize <= 0) ? row.getPhysicalNumberOfCells() : cellSize; //Establecer el nmero de columnas que quiero optener de la fila.

            for (int i = 0; i < numColumns; i++) {
                cell = Excel.getCell(row, i);
                resultado.add(Excel.getCellValue(cell));
            }
        }
    }

    return resultado;
}

From source file:ve.zoonosis.model.imports.CasosDiarioPorMunicipio.java

License:Apache License

@Override
public void run() {
    /*//from  w  w w . j ava2  s  .  c  o m
            
     * Obtenemos la primera pestaa a la que se quiera procesar indicando el indice.
     * Una vez obtenida la hoja excel con las filas que se quieren leer obtenemos el iterator   
     * que nos permite recorrer cada una de las filas que contiene.   
     */
    HSSFSheet sheet = workbook.getSheetAt(0);

    for (int i = 2; i < sheet.getPhysicalNumberOfRows() - 6; i++) {
        Row r = sheet.getRow(i);
        for (int j = 1; j < r.getPhysicalNumberOfCells(); j++) {

            Cell c = r.getCell(j);

            if (c == null) {
                continue;
            }

            cargarObjects(sheet, i, j, obtenrValor(c));

        }
    }
    finalizar();
}

From source file:ve.zoonosis.model.imports.VacunadosDiarioPorMunicipio.java

License:Apache License

@Override
public void run() {
    /*//from w w w  .  j a v  a  2 s .  c o m
            
     * Obtenemos la primera pestaa a la que se quiera procesar indicando el indice.
     * Una vez obtenida la hoja excel con las filas que se quieren leer obtenemos el iterator   
     * que nos permite recorrer cada una de las filas que contiene.   
     */

    for (int z = 0; z < workbook.getNumberOfSheets(); z++) {
        vacunacion = new HashMap<>();
        HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(z);
        for (int i = 2; i < sheet.getPhysicalNumberOfRows() - 6; i++) {
            Row r = sheet.getRow(i);
            for (int j = 1; j < r.getPhysicalNumberOfCells(); j++) {
                Cell c = r.getCell(j);
                if (c == null) {
                    continue;
                }
                try {
                    cargarObjects(sheet, i, j, obtenrValor(c));
                } catch (ParseException ex) {
                    Logger.getLogger(VacunadosDiarioPorMunicipio.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }
        incremntarLista();
    }
    finalizar();
}

From source file:xlsParser.hffsimpl.SSReader.java

private String[] parseRow(Row row, int n) {
    if (n <= 0)
        n = row.getPhysicalNumberOfCells();

    String[] data = new String[n];
    for (int i = 0; i < data.length; ++i) {
        Cell c = row.getCell(i);/*from ww  w  .ja  v  a  2  s .c  o m*/
        data[i] = cellToString(c);
    }

    return data;
}