Example usage for org.apache.poi.ss.usermodel Cell getRow

List of usage examples for org.apache.poi.ss.usermodel Cell getRow

Introduction

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

Prototype

Row getRow();

Source Link

Document

Returns the Row this cell belongs to

Usage

From source file:org.drugepi.table.ExcelUtils.java

License:Mozilla Public License

public static void formatNumericCell(Cell cell, String s, String[] excelFormats) {
    CellStyle origStyle = cell.getCellStyle();
    CellStyle newStyle = cell.getRow().getSheet().getWorkbook().createCellStyle();
    DataFormat newFormat = cell.getRow().getSheet().getWorkbook().createDataFormat();
    newStyle.cloneStyleFrom(origStyle);// www  .j  a va  2  s  .  com

    newStyle.setAlignment(CellStyle.ALIGN_LEFT);

    int numDecimals = -1;
    if (s != null) {
        int decimalIndex = s.indexOf(".");
        if (decimalIndex >= 0)
            numDecimals = s.length() - decimalIndex - 1;
    }

    if (numDecimals < 0)
        numDecimals = 0;

    if ((numDecimals >= 0) && (numDecimals <= 8))
        newStyle.setDataFormat(newFormat.getFormat(excelFormats[numDecimals]));

    cell.setCellStyle(newStyle);
}

From source file:org.hellojavaer.poi.excel.utils.ExcelUtils.java

License:Apache License

@SuppressWarnings("unused")
private static void writeCell(Cell cell, Object val, boolean userTemplate,
        ExcelWriteFieldMappingAttribute attribute, Object bean) {
    if (attribute != null && attribute.getLinkField() != null) {
        String addressFieldName = attribute.getLinkField();
        String address = null;/*from w w  w .  java2 s.c o  m*/
        if (bean != null) {
            address = (String) getFieldValue(bean, addressFieldName, true);
        }
        Workbook wb = cell.getRow().getSheet().getWorkbook();

        Hyperlink link = wb.getCreationHelper().createHyperlink(attribute.getLinkType());
        link.setAddress(address);
        cell.setHyperlink(link);
        // Its style can't inherit from cell.
        CellStyle style = wb.createCellStyle();
        Font hlinkFont = wb.createFont();
        hlinkFont.setUnderline(Font.U_SINGLE);
        hlinkFont.setColor(IndexedColors.BLUE.getIndex());
        style.setFont(hlinkFont);
        if (cell.getCellStyle() != null) {
            style.setFillBackgroundColor(cell.getCellStyle().getFillBackgroundColor());
        }
        cell.setCellStyle(style);
    }
    if (val == null) {
        cell.setCellValue((String) null);
        return;
    }
    Class<?> clazz = val.getClass();
    if (val instanceof Byte) {// Double
        Byte temp = (Byte) val;
        cell.setCellValue((double) temp.byteValue());
    } else if (val instanceof Short) {
        Short temp = (Short) val;
        cell.setCellValue((double) temp.shortValue());
    } else if (val instanceof Integer) {
        Integer temp = (Integer) val;
        cell.setCellValue((double) temp.intValue());
    } else if (val instanceof Long) {
        Long temp = (Long) val;
        cell.setCellValue((double) temp.longValue());
    } else if (val instanceof Float) {
        Float temp = (Float) val;
        cell.setCellValue((double) temp.floatValue());
    } else if (val instanceof Double) {
        Double temp = (Double) val;
        cell.setCellValue((double) temp.doubleValue());
    } else if (val instanceof Date) {// Date
        Date dateVal = (Date) val;
        long time = dateVal.getTime();
        // read is based on 1899/12/31 but DateUtil.getExcelDate is base on
        // 1900/01/01
        if (time >= TIME_1899_12_31_00_00_00_000 && time < TIME_1900_01_01_00_00_00_000) {
            Date incOneDay = new Date(time + 24 * 60 * 60 * 1000);
            double d = DateUtil.getExcelDate(incOneDay);
            cell.setCellValue(d - 1);
        } else {
            cell.setCellValue(dateVal);
        }

        if (!userTemplate) {
            Workbook wb = cell.getRow().getSheet().getWorkbook();
            CellStyle cellStyle = cell.getCellStyle();
            if (cellStyle == null) {
                cellStyle = wb.createCellStyle();
            }
            DataFormat dataFormat = wb.getCreationHelper().createDataFormat();
            // @see #BuiltinFormats
            // 0xe, "m/d/yy"
            // 0x14 "h:mm"
            // 0x16 "m/d/yy h:mm"
            // {@linke https://en.wikipedia.org/wiki/Year_10,000_problem}
            /** [1899/12/31 00:00:00:000~1900/01/01 00:00:000) */
            if (time >= TIME_1899_12_31_00_00_00_000 && time < TIME_1900_01_02_00_00_00_000) {
                cellStyle.setDataFormat(dataFormat.getFormat("h:mm"));
                // cellStyle.setDataFormat(dataFormat.getFormat("m/d/yy h:mm"));
            } else {
                // if ( time % (24 * 60 * 60 * 1000) == 0) {//for time
                // zone,we can't use this way.
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(dateVal);
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int minute = calendar.get(Calendar.MINUTE);
                int second = calendar.get(Calendar.SECOND);
                int millisecond = calendar.get(Calendar.MILLISECOND);
                if (millisecond == 0 && second == 0 && minute == 0 && hour == 0) {
                    cellStyle.setDataFormat(dataFormat.getFormat("m/d/yy"));
                } else {
                    cellStyle.setDataFormat(dataFormat.getFormat("m/d/yy h:mm"));
                }
            }
            cell.setCellStyle(cellStyle);
        }
    } else if (val instanceof Boolean) {// Boolean
        cell.setCellValue(((Boolean) val).booleanValue());
    } else {// String
        cell.setCellValue((String) val.toString());
    }
}

From source file:org.isisaddons.module.excel.dom.CellMarshaller.java

License:Apache License

private static void setCellComment(final Cell cell, final String commentText) {
    Sheet sheet = cell.getSheet();/*from w  w  w.j ava 2  s .  com*/
    Row row = cell.getRow();
    Workbook workbook = sheet.getWorkbook();
    CreationHelper creationHelper = workbook.getCreationHelper();
    ClientAnchor anchor = creationHelper.createClientAnchor();
    anchor.setCol1(cell.getColumnIndex());
    anchor.setCol2(cell.getColumnIndex() + 1);
    anchor.setRow1(row.getRowNum());
    anchor.setRow2(row.getRowNum() + 3);

    Drawing drawing = sheet.createDrawingPatriarch();
    Comment comment1 = drawing.createCellComment(anchor);

    RichTextString commentRtf = creationHelper.createRichTextString(commentText);

    comment1.setString(commentRtf);
    Comment comment = comment1;
    cell.setCellComment(comment);
}

From source file:org.joeffice.spreadsheet.cell.CellRenderer.java

License:Apache License

public void decorateLabel(Cell cell, JLabel defaultRenderer) {

    // Text/*from w  ww . j  av  a  2  s  .c  o  m*/
    // String text = getFormattedText(cell);
    // XXX small bug with decimal not using the correct comma's
    if (cell.getCellType() == Cell.CELL_TYPE_FORMULA && formulaEvaluator == null) {
        formulaEvaluator = cell.getRow().getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
    }
    String text = DATA_FORMATTER.formatCellValue(cell, formulaEvaluator);
    setText(text);

    decorateComponent(cell, this, defaultRenderer);

    // Alignment
    CellStyle style = cell.getCellStyle();
    short alignment = style.getAlignment();
    if (alignment == CellStyle.ALIGN_CENTER || cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
        setHorizontalAlignment(SwingConstants.CENTER);
    } else if (alignment == CellStyle.ALIGN_RIGHT || cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        setHorizontalAlignment(SwingConstants.RIGHT);
    } else {
        setHorizontalAlignment(defaultRenderer.getHorizontalAlignment());
    }
    short verticalAlignment = style.getAlignment(); // Either LibreOffice 4 or POI has problem with vertical alignment
    if (verticalAlignment == CellStyle.VERTICAL_TOP) {
        setVerticalAlignment(SwingConstants.TOP);
    } else if (verticalAlignment == CellStyle.VERTICAL_CENTER) {
        setVerticalAlignment(SwingConstants.CENTER);
    } else if (verticalAlignment == CellStyle.VERTICAL_BOTTOM) {
        setVerticalAlignment(SwingConstants.BOTTOM);
    } else {
        setVerticalAlignment(defaultRenderer.getVerticalAlignment());
    }
}

From source file:org.tiefaces.components.websheet.dataobjects.CellMap.java

License:MIT License

@Override
public final Object put(final Object key, final Object value) {
    try {//  www  .j  a  v a 2  s . c  om
        CellMapKey mkey = new CellMapKey((String) key);
        if (!mkey.isParseSuccess()) {
            return null;
        }
        Cell poiCell = parent.getCellHelper().getPoiCellWithRowColFromCurrentPage(mkey.getRowIndex(),
                mkey.getColIndex());
        if (poiCell == null) {
            return null;
        }
        String oldValue = CellUtility.getCellValueWithoutFormat(poiCell);
        FacesCell facesCell = parent.getCellHelper().getFacesCellWithRowColFromCurrentPage(mkey.getRowIndex(),
                mkey.getColIndex());
        String newValue = assembleNewValue(value, facesCell);
        if (newValue != null && !newValue.equals(oldValue)) {
            CellUtility.setCellValue(poiCell, newValue);
            if (facesCell.isHasSaveAttr()) {
                parent.getCellHelper().saveDataInContext(poiCell, newValue);
            }
            // patch to avoid not updated downloaded file
            CellUtility.copyCell(poiCell.getSheet(), poiCell.getRow(), poiCell.getRow(),
                    poiCell.getColumnIndex(), false);
            parent.getCellHelper().reCalc();
        }

        return value;
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "Save cell data error : " + ex.getLocalizedMessage(), ex);
    }
    return null;
}

From source file:org.tiefaces.components.websheet.service.CellHelper.java

License:MIT License

/**
 * Save data in context.// w  ww. j  a v a  2  s . c om
 *
 * @param poiCell
 *            the poi cell
 * @param strValue
 *            the str value
 */
public final void saveDataInContext(final Cell poiCell, final String strValue) {

    String saveAttr = SaveAttrsUtility.prepareContextAndAttrsForCell(poiCell,
            ConfigurationUtility.getFullNameFromRow(poiCell.getRow()), this);
    if (saveAttr != null) {
        SaveAttrsUtility.saveDataToObjectInContext(parent.getSerialDataContext().getDataContext(), saveAttr,
                strValue, parent.getExpEngine());
        parent.getHelper().getWebSheetLoader().setUnsavedStatus(RequestContext.getCurrentInstance(), true);
    }
}

From source file:org.tiefaces.components.websheet.service.ValidationHandler.java

License:MIT License

/**
 * Validate by tie web sheet validation bean.
 *
 * @param poiCell the poi cell// ww w.  j a  v  a2s. c o  m
 * @param topRow the top row
 * @param leftCol the left col
 * @param cell the cell
 * @param value the value
 * @param updateGui the update gui
 * @return true, if successful
 */
private boolean validateByTieWebSheetValidationBean(final Cell poiCell, final int topRow, final int leftCol,
        final FacesCell cell, final String value, boolean updateGui) {
    if (parent.getTieWebSheetValidationBean() != null) {
        String errormsg = null;
        String fullName = ConfigurationUtility.getFullNameFromRow(poiCell.getRow());
        String saveAttr = SaveAttrsUtility.prepareContextAndAttrsForCell(poiCell, fullName,
                parent.getCellHelper());
        if (saveAttr != null) {
            int row = poiCell.getRowIndex();
            int col = poiCell.getColumnIndex();
            errormsg = parent.getTieWebSheetValidationBean().validate(
                    parent.getSerialDataContext().getDataContext(), saveAttr,
                    ConfigurationUtility.getFullNameFromRow(poiCell.getRow()),
                    poiCell.getSheet().getSheetName(), row, col, value);
            if ((errormsg != null) && (!errormsg.isEmpty())) {
                cell.setErrormsg(errormsg);
                refreshAfterStatusChanged(false, true, row - topRow, col - leftCol, cell, updateGui);
                return false;
            }
        }
    }
    return true;
}

From source file:org.tiefaces.components.websheet.utility.CommandUtility.java

License:MIT License

private static void createTieCell(final Cell cell, final Map<String, Object> context,
        final ExpressionEngine engine) {

    @SuppressWarnings("unchecked")
    HashMap<String, TieCell> tieCells = (HashMap<String, TieCell>) context.get("tiecells");

    // if tiecells exists is because tieWebSheetBean.isAdvancedContext() is
    // true//from  www . j av  a  2 s.c o m
    if (tieCells != null) {

        if (SaveAttrsUtility.isHasSaveAttr(cell)) {

            String saveAttrList = SaveAttrsUtility.getSaveAttrListFromRow(cell.getRow());

            if (saveAttrList != null) {
                String saveAttr = SaveAttrsUtility.getSaveAttrFromList(cell.getColumnIndex(), saveAttrList);
                if (saveAttr != null) {

                    int index = saveAttr.lastIndexOf('.');
                    if (index > 0) {
                        String strObject = saveAttr.substring(0, index);
                        String strMethod = saveAttr.substring(index + 1);
                        strObject = "${" + strObject + "}";

                        Object object = CommandUtility.evaluate(strObject, context, engine);

                        if (object != null) {
                            TieCell tieCell = CellUtility.getOrAddTieCellInMap(cell, tieCells);
                            tieCell.setContextObject(object);
                            tieCell.setObjectStr(strObject);
                            tieCell.setMethodStr(strMethod);
                        }

                    }

                }
            }

        }

    }
}

From source file:org.tiefaces.components.websheet.utility.ConfigurationUtility.java

License:MIT License

/**
 * Setup upper level formula./*  w w  w . ja v a2s.co  m*/
 *
 * @param cell
 *            cell.
 * @param originFormula
 *            originFormula.
 * @param actionFullName
 *            add full name.
 * @param rowsMap
 *            rowsmap.
 * @param configBuildRef
 *            config build ref.
 */
private static void setupUpperLevelFormula(final Cell cell, final String originFormula,
        final String actionFullName, final Map<String, List<RowsMapping>> rowsMap,
        final ConfigBuildRef configBuildRef) {
    String fullName = getFullNameFromRow(cell.getRow());
    // check wither it's upper level
    if (actionFullName.startsWith(fullName + ":")) {
        // get rows mapping for upper level row
        List<RowsMapping> currentRowsMappingList = rowsMap.get(fullName);
        if (currentRowsMappingList == null) {
            currentRowsMappingList = gatherRowsMappingByFullName(configBuildRef, fullName);
            rowsMap.put(fullName, currentRowsMappingList);
        }
        ShiftFormulaRef shiftFormulaRef = new ShiftFormulaRef(configBuildRef.getWatchList(),
                currentRowsMappingList);
        shiftFormulaRef.setFormulaChanged(0);
        buildCellFormulaForShiftedRows(configBuildRef.getSheet(), configBuildRef.getWbWrapper(),
                shiftFormulaRef, cell, originFormula);
        if (shiftFormulaRef.getFormulaChanged() > 0) {
            configBuildRef.getCachedCells().put(cell, originFormula);
        }

    }
}

From source file:org.tiefaces.components.websheet.utility.SaveAttrsUtility.java

License:MIT License

/**
 * Checks if is checks for save attr.//from  w ww .  j  av  a 2  s. c  om
 *
 * @param cell
 *            the cell
 * @return true, if is checks for save attr
 */
public static boolean isHasSaveAttr(final Cell cell) {
    Cell saveAttrCell = cell.getRow().getCell(TieConstants.HIDDEN_SAVE_OBJECTS_COLUMN);
    if (saveAttrCell != null) {
        return isHasSaveAttr(cell, saveAttrCell.getStringCellValue());
    }
    return false;
}