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

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

Introduction

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

Prototype

int getRowIndex();

Source Link

Document

Returns row index of a row in the sheet that contains this cell

Usage

From source file:org.bbreak.excella.reports.tag.RemoveParamParser.java

License:Open Source License

@Override
public ParsedReportInfo parse(Sheet sheet, Cell tagCell, Object data) throws ParseException {
    // ????//from   w  w w. jav a  2  s  .  co  m
    ParsedReportInfo parsedReportInfo = new ParsedReportInfo();
    parsedReportInfo.setRowIndex(tagCell.getRowIndex());
    parsedReportInfo.setColumnIndex(tagCell.getColumnIndex());
    parsedReportInfo.setDefaultRowIndex(tagCell.getRowIndex());
    parsedReportInfo.setDefaultColumnIndex(tagCell.getColumnIndex());
    return parsedReportInfo;
}

From source file:org.bbreak.excella.reports.tag.RowRepeatParamParser.java

License:Open Source License

@Override
public ParsedReportInfo parse(Sheet sheet, Cell tagCell, Object data) throws ParseException {

    Map<String, String> paramDef = TagUtil.getParams(tagCell.getStringCellValue());

    // ?//from   w  w  w  .j a  v a  2  s . c  o  m
    checkParam(paramDef, tagCell);

    String tag = tagCell.getStringCellValue();
    ReportsParserInfo reportsParserInfo = (ReportsParserInfo) data;
    // ?
    Object[] paramValues = null;
    try {
        // ?
        boolean rowShift = false;
        if (paramDef.containsKey(PARAM_ROW_SHIFT)) {
            rowShift = Boolean.valueOf(paramDef.get(PARAM_ROW_SHIFT));
        }
        // ??
        boolean hideDuplicate = false;
        if (paramDef.containsKey(PARAM_DUPLICATE)) {
            hideDuplicate = Boolean.valueOf(paramDef.get(PARAM_DUPLICATE));
        }
        // ?
        Integer breakNum = null;
        if (paramDef.containsKey(PARAM_BREAK_NUM)) {
            breakNum = Integer.valueOf(paramDef.get(PARAM_BREAK_NUM));
        }
        // 
        boolean changeBreak = false;
        if (paramDef.containsKey(PARAM_CHANGE_BREAK)) {
            changeBreak = Boolean.valueOf(paramDef.get(PARAM_CHANGE_BREAK));
        }
        // ?
        Integer repeatNum = null;
        if (paramDef.containsKey(PARAM_REPEAT_NUM)) {
            repeatNum = Integer.valueOf(paramDef.get(PARAM_REPEAT_NUM));
        }
        // ??
        Integer minRepeatNum = null;
        if (paramDef.containsKey(PARAM_MIN_REPEAT_NUM)) {
            minRepeatNum = Integer.valueOf(paramDef.get(PARAM_MIN_REPEAT_NUM));
        }
        // ?
        boolean sheetLink = false;
        if (paramDef.containsKey(PARAM_SHEET_LINK)) {
            sheetLink = Boolean.valueOf(paramDef.get(PARAM_SHEET_LINK));
        }
        // 
        String propertyName = null;
        if (paramDef.containsKey(PARAM_PROPERTY)) {
            propertyName = paramDef.get(PARAM_PROPERTY);
        }
        // ???
        String replaceParam = paramDef.get(PARAM_VALUE);
        // 
        if (ReportsUtil.VALUE_SHEET_NAMES.equals(replaceParam)) {
            // ??
            paramValues = ReportsUtil.getSheetNames(reportsParserInfo.getReportBook()).toArray();
        } else if (ReportsUtil.VALUE_SHEET_VALUES.equals(replaceParam)) {
            // 
            paramValues = ReportsUtil.getSheetValues(reportsParserInfo.getReportBook(), propertyName,
                    reportsParserInfo.getReportParsers()).toArray();
        } else {
            // ???
            ParamInfo paramInfo = reportsParserInfo.getParamInfo();
            if (paramInfo != null) {
                paramValues = getParamData(paramInfo, replaceParam);
            }
        }

        if (paramValues == null || paramValues.length == 0) {
            // ?
            paramValues = new Object[] { null };
        }

        // ?
        int shiftNum = paramValues.length;
        // ?
        int paramLength = paramValues.length;

        // ???????
        if (minRepeatNum != null && shiftNum < minRepeatNum) {
            Object[] tmpValues = new Object[minRepeatNum];
            System.arraycopy(paramValues, 0, tmpValues, 0, paramValues.length);
            paramValues = tmpValues;
            shiftNum = paramValues.length;
            paramLength = paramValues.length;
        }

        // ???
        int defaultFromCellRowIndex = tagCell.getRowIndex();
        // ???
        int defaultFromCellColIndex = tagCell.getColumnIndex();

        // ???
        int unitRowSize = 1;

        // ???
        List<CellRangeAddress> maegedAddresses = new ArrayList<CellRangeAddress>();
        for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
            CellRangeAddress targetAddress = sheet.getMergedRegion(i);
            maegedAddresses.add(targetAddress);
        }

        // ???
        if (maegedAddresses.size() > 0) {
            // ?????????????
            for (CellRangeAddress curMergedAdress : maegedAddresses) {
                if (defaultFromCellColIndex == curMergedAdress.getFirstColumn()
                        && defaultFromCellRowIndex == curMergedAdress.getFirstRow()) {
                    // ????????????
                    // ??????
                    unitRowSize = curMergedAdress.getLastRow() - curMergedAdress.getFirstRow() + 1;

                    // ??????
                    shiftNum = shiftNum * unitRowSize;
                }
            }
        }

        // ???
        // ?????
        tagCell = new CellClone(tagCell);
        List<Cell> cellList = new ArrayList<Cell>();
        int defaultToOverCellRowIndex = tagCell.getRowIndex() + unitRowSize;
        for (int i = defaultFromCellRowIndex; i < defaultToOverCellRowIndex; i++) {
            Row targetCellRow = sheet.getRow(i);
            cellList.add(new CellClone(targetCellRow.getCell(tagCell.getColumnIndex())));
        }

        // ?
        if (repeatNum != null && repeatNum < shiftNum) {
            // ??????
            // ????????????????
            // ?????
            shiftNum = repeatNum * unitRowSize;

            // ??????
            paramLength = repeatNum;
        }

        // ?
        if (shiftNum > 1) {
            // ?(????????)
            int shiftRowSize = tagCell.getRowIndex() + shiftNum - unitRowSize - 1;
            if (!rowShift) {
                // ?????
                CellRangeAddress rangeAddress = new CellRangeAddress(tagCell.getRowIndex(), shiftRowSize,
                        tagCell.getColumnIndex(), tagCell.getColumnIndex());
                PoiUtil.insertRangeDown(sheet, rangeAddress);
            } else {
                // ?????
                // #35 POI???????????????????
                // ??????0????????
                CellRangeAddress rangeAddress = new CellRangeAddress(tagCell.getRowIndex() + unitRowSize,
                        tagCell.getRowIndex() + shiftNum - 1, 0, PoiUtil.getLastColNum(sheet));
                PoiUtil.insertRangeDown(sheet, rangeAddress);
                // int shiftStartRow = tagCell.getRowIndex() + 1;
                // int shiftEndRow = sheet.getLastRowNum();
                // if ( shiftEndRow < shiftStartRow) {
                // // ????????????????
                // // ????????????
                // shiftEndRow = shiftStartRow + 1;
                // }
                // sheet.shiftRows( shiftStartRow, shiftEndRow, shiftNum - unitRowSize);
            }
        }

        // ???
        Workbook workbook = sheet.getWorkbook();
        String sheetName = workbook.getSheetName(workbook.getSheetIndex(sheet));
        // ??
        List<String> sheetNames = ReportsUtil.getSheetNames(reportsParserInfo.getReportBook());
        // ?
        List<Object> resultValues = new ArrayList<Object>();
        // ??(beforeValue)
        Object beforeValue = null;

        // ?
        int valueIndex = -1;
        // ?????
        for (int rowIndex = 0; rowIndex < shiftNum; rowIndex++) {
            // ??
            Row row = sheet.getRow(tagCell.getRowIndex() + rowIndex);
            if (row == null) {
                row = sheet.createRow(tagCell.getRowIndex() + rowIndex);
            }
            // ??
            Cell cell = row.getCell(tagCell.getColumnIndex());
            if (cell == null) {
                cell = row.createCell(tagCell.getColumnIndex());
            }
            // ????(null)
            Object value = null;

            // ??????
            // ??0???(?????????)???????
            int cellIndex = rowIndex % unitRowSize;

            // ?????????
            boolean skipRow = false;
            if (cellIndex != 0) {
                skipRow = true;
            } else {
                valueIndex++;
            }

            // (?)
            PoiUtil.copyCell(cellList.get(cellIndex), cell);

            // ?
            Object currentValue = paramValues[valueIndex];
            // ??=true???????????
            boolean duplicateValue = false;
            if (beforeValue != null && currentValue != null && beforeValue.equals(currentValue)) {
                // ???
                duplicateValue = true;
            }
            if (!skipRow && !(hideDuplicate && duplicateValue)) {
                // ??=true
                // ??????????????
                value = currentValue;
            }
            if (log.isDebugEnabled()) {
                log.debug("[??=" + sheetName + ",=(" + cell.getRowIndex() + ","
                        + cell.getColumnIndex() + ")]  " + tag + "  " + value);
            }
            PoiUtil.setCellValue(cell, value);
            resultValues.add(value);

            // ?
            if (sheetLink) {
                if (!skipRow && valueIndex < sheetNames.size()) {
                    PoiUtil.setHyperlink(cell, HyperlinkType.DOCUMENT,
                            "'" + sheetNames.get(valueIndex) + "'!A1");
                    if (log.isDebugEnabled()) {
                        log.debug("[??=" + sheetName + ",=(" + cell.getRowIndex() + ","
                                + cell.getColumnIndex() + ")]  Hyperlink  " + "'"
                                + sheetNames.get(valueIndex) + "'!A1");
                    }
                }
            }

            // 
            if (!skipRow) {
                if (breakNum != null && valueIndex != 0 && valueIndex % breakNum == 0) {
                    // ???
                    sheet.setRowBreak(row.getRowNum() - 1);
                }
                if (changeBreak && valueIndex != 0 && !duplicateValue) {
                    // ???
                    sheet.setRowBreak(row.getRowNum() - 1);
                }
            }

            // ??
            // ??????????
            // ????????????
            if (!skipRow && unitRowSize > 1) {
                // ???
                boolean mergedRegionFlag = false;
                if (rowShift && valueIndex != 0) {
                    // ?????????????
                    mergedRegionFlag = true;
                } else if (!rowShift && paramLength > valueIndex + 1) {
                    // ????????????
                    mergedRegionFlag = true;
                }

                // ??
                if (mergedRegionFlag) {
                    CellRangeAddress rangeAddress = new CellRangeAddress(cell.getRowIndex(),
                            cell.getRowIndex() + unitRowSize - 1, cell.getColumnIndex(), cell.getColumnIndex());
                    sheet.addMergedRegion(rangeAddress);

                    // ????????????
                    beforeValue = currentValue;
                }
            }

            // ???????
            if (unitRowSize == 1) {
                beforeValue = currentValue;
            }

        }

        // ????
        ParsedReportInfo parsedReportInfo = new ParsedReportInfo();
        parsedReportInfo.setParsedObject(resultValues);
        // ??
        parsedReportInfo.setDefaultRowIndex(tagCell.getRowIndex() + unitRowSize - 1);
        parsedReportInfo.setDefaultColumnIndex(tagCell.getColumnIndex());
        parsedReportInfo.setRowIndex(tagCell.getRowIndex() + shiftNum - 1);
        parsedReportInfo.setColumnIndex(tagCell.getColumnIndex());
        if (log.isDebugEnabled()) {
            log.debug(parsedReportInfo);
        }

        return parsedReportInfo;

    } catch (Exception e) {
        throw new ParseException(tagCell, e);
    }
}

From source file:org.bbreak.excella.reports.tag.SingleParamParser.java

License:Open Source License

@Override
public ParsedReportInfo parse(Sheet sheet, Cell tagCell, Object data) throws ParseException {
    List<String> tmpTargets = new ArrayList<String>();
    StringTokenizer tagTokenizer = new StringTokenizer(tagCell.getStringCellValue(), getTag());
    while (tagTokenizer.hasMoreTokens()) {
        tmpTargets.add(tagTokenizer.nextToken());
    }/*from  w ww . ja  v a  2s. co  m*/

    List<String> finalTargets = new ArrayList<String>();
    for (String tempTarget : tmpTargets) {
        if (tempTarget.startsWith(TagParser.TAG_PARAM_PREFIX)
                && !tempTarget.endsWith(TagParser.TAG_PARAM_SUFFIX)) {
            finalTargets.add(tempTarget.substring(0, tempTarget.indexOf(TagParser.TAG_PARAM_SUFFIX) + 1));
            finalTargets.add(tempTarget.substring(tempTarget.indexOf(TagParser.TAG_PARAM_SUFFIX) + 1));
            continue;
        }
        finalTargets.add(tempTarget);
    }

    ParsedReportInfo parsedReportInfo = new ParsedReportInfo();
    List<Object> paramValues = new ArrayList<Object>();

    for (int i = 0; i < finalTargets.size(); i++) {
        String target = finalTargets.get(i);
        if (!target.startsWith(TagParser.TAG_PARAM_PREFIX)) {
            // ???
            paramValues.add(target);
            continue;
        } else {
            // ?????
            target = getTag() + target;
        }

        Map<String, String> paramDef = TagUtil.getParams(target);

        // ?
        checkParam(paramDef, tagCell);

        ReportsParserInfo reportsParserInfo = (ReportsParserInfo) data;

        ParamInfo paramInfo = reportsParserInfo.getParamInfo();

        if (paramInfo != null) {
            // ???
            String replaceParam = paramDef.get(PARAM_VALUE);

            // ???
            paramValues.add(getParamData(paramInfo, replaceParam));

            if (log.isDebugEnabled()) {
                Workbook workbook = sheet.getWorkbook();
                String sheetName = workbook.getSheetName(workbook.getSheetIndex(sheet));
                log.debug("[??=" + sheetName + ",=(" + tagCell.getRowIndex() + ","
                        + tagCell.getColumnIndex() + ")] " + tagCell.getStringCellValue() + "  "
                        + paramValues.get(i));
            }
        }
    }

    // ?
    if (paramValues.size() > 1) {
        StringBuilder builder = new StringBuilder();
        for (Object object : paramValues) {
            if (object == null) {
                continue;
            }
            if (object instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                builder.append(sdf.format(object));
                continue;
            }
            builder.append(object);
        }
        PoiUtil.setCellValue(tagCell, builder.toString());
        parsedReportInfo.setParsedObject(builder.toString());
    } else if (paramValues.size() == 1) {
        PoiUtil.setCellValue(tagCell, paramValues.get(0));
        parsedReportInfo.setParsedObject(paramValues.get(0));
    }
    parsedReportInfo.setDefaultRowIndex(tagCell.getRowIndex());
    parsedReportInfo.setDefaultColumnIndex(tagCell.getColumnIndex());
    parsedReportInfo.setRowIndex(tagCell.getRowIndex());
    parsedReportInfo.setColumnIndex(tagCell.getColumnIndex());

    return parsedReportInfo;
}

From source file:org.bbreak.excella.reports.tag.SumParamParser.java

License:Open Source License

@Override
public ParsedReportInfo parse(Sheet sheet, Cell tagCell, Object data) throws ParseException {

    Map<String, String> paramDef = TagUtil.getParams(tagCell.getStringCellValue());

    ReportsParserInfo reportsParserInfo = (ReportsParserInfo) data;

    ParamInfo paramInfo = reportsParserInfo.getParamInfo();

    Object paramValue = null;//from w  w w  .  j av a2  s.c om

    if (paramInfo != null) {
        // ?
        // ???
        String replaceParam = paramDef.get(PARAM_VALUE);

        paramValue = ReportsUtil.getSumValue(paramInfo, replaceParam, reportsParserInfo.getReportParsers());

        // ?
        PoiUtil.setCellValue(tagCell, paramValue);

    }

    // ????
    ParsedReportInfo parsedReportInfo = new ParsedReportInfo();
    parsedReportInfo.setParsedObject(paramValue);
    parsedReportInfo.setRowIndex(tagCell.getRowIndex());
    parsedReportInfo.setColumnIndex(tagCell.getColumnIndex());
    parsedReportInfo.setDefaultRowIndex(tagCell.getRowIndex());
    parsedReportInfo.setDefaultColumnIndex(tagCell.getColumnIndex());

    return parsedReportInfo;
}

From source file:org.bbreak.excella.trans.tag.sheet2java.SheetToJavaParser.java

License:Open Source License

/**
 * ?/*from w  ww. j ava  2  s  .  co  m*/
 * 
 * @param sheet 
 * @param tagCell ???
 * @param data TransProcessor?processBook, processSheet?<BR> 
 *              ????TagParser.parse??????<BR>
 * @return ?
 * @throws ParseException 
 */
@Override
public List<SheetToJavaParseInfo> parse(Sheet sheet, Cell tagCell, Object data) throws ParseException {
    // ?
    int tagRowIdx = tagCell.getRowIndex();
    int tagColIdx = tagCell.getColumnIndex();

    int valueRowFromIdx;
    int valueRowToIdx = sheet.getLastRowNum();

    // ????
    String settingTagName = getTag() + DEFAULT_SETTING_SUFFIX;

    try {
        Map<String, String> paramDef = TagUtil.getParams(tagCell.getStringCellValue());

        // ?
        valueRowFromIdx = TagUtil.adjustValue(tagRowIdx, paramDef, PARAM_DATA_ROW_FROM,
                DEFAULT_DATA_ROW_FROM_ADJUST);
        if (valueRowFromIdx < 0 || valueRowFromIdx > sheet.getLastRowNum()) {
            throw new ParseException(tagCell, "?" + PARAM_DATA_ROW_FROM);
        }

        // ?
        valueRowToIdx = TagUtil.adjustValue(tagRowIdx, paramDef, PARAM_DATA_ROW_TO, valueRowToIdx - tagRowIdx);
        if (valueRowToIdx > sheet.getLastRowNum() || valueRowToIdx < 0) {
            throw new ParseException(tagCell, "?" + PARAM_DATA_ROW_TO);
        }

        // ???
        if (valueRowFromIdx > valueRowToIdx) {
            throw new ParseException(tagCell,
                    "?" + PARAM_DATA_ROW_FROM + "," + PARAM_DATA_ROW_TO);
        }

        // ????
        if (paramDef.containsKey(PARAM_SETTING_TAG_NAME)) {
            settingTagName = paramDef.get(PARAM_SETTING_TAG_NAME);
        }

        // ?
        if (paramDef.containsKey(PARAM_RESULT_KEY)) {
            // ???????
            throw new ParseException(tagCell, PARAM_RESULT_KEY + "????????");
        }

    } catch (Exception e) {
        if (e instanceof ParseException) {
            throw (ParseException) e;
        } else {
            throw new ParseException(tagCell, e);
        }
    }

    List<SheetToJavaParseInfo> sheetInfoList = new ArrayList<SheetToJavaParseInfo>();

    // ??
    int sheetNameColIdx = tagColIdx++;
    // ???No
    int logicalRowColIdx = tagColIdx++;
    // No
    int dataRowColIdx = tagColIdx;

    // ?????
    Workbook workbook = sheet.getWorkbook();

    // ???
    for (int rowNum = valueRowFromIdx; rowNum <= valueRowToIdx; rowNum++) {
        Row row = sheet.getRow(rowNum);
        if (row != null) {
            // ??
            Cell sheetNameCell = row.getCell(sheetNameColIdx);
            Cell logicalRowNumCell = row.getCell(logicalRowColIdx);
            Cell valueRowNumCell = row.getCell(dataRowColIdx);

            // ?
            if ((sheetNameCell == null) && (logicalRowNumCell == null) && (valueRowNumCell == null)) {
                // ????null??
                continue;

            } else if ((sheetNameCell == null) || (sheetNameCell.getStringCellValue() == null)
                    || ("".equals(sheetNameCell.getStringCellValue()))) {
                // ?????????
                continue;

            } else {
                // ????
                Cell requiredErrorCell = null;
                if (logicalRowNumCell == null) {
                    requiredErrorCell = row.createCell(logicalRowColIdx);
                } else if (valueRowNumCell == null) {
                    requiredErrorCell = row.createCell(dataRowColIdx);
                }

                // ??????
                if (requiredErrorCell != null) {
                    throw new ParseException(requiredErrorCell, "?null??");
                }
            }

            // ???No?
            int logicalRowNum;
            try {
                logicalRowNum = (Integer) PoiUtil.getCellValue(logicalRowNumCell, Integer.class);
            } catch (Exception e) {
                throw new ParseException(logicalRowNumCell, e);
            }

            // No?
            int valueRowNum;
            try {
                valueRowNum = (Integer) PoiUtil.getCellValue(valueRowNumCell, Integer.class);
            } catch (Exception e) {
                throw new ParseException(valueRowNumCell, e);
            }

            // ???
            String sheetName = sheetNameCell.getStringCellValue();
            if (workbook.getSheet(sheetName) == null) {
                throw new ParseException(sheetNameCell, "[" + sheetName + "]????");
            }

            // 
            SheetToJavaParseInfo sheetInfo = new SheetToJavaParseInfo();
            sheetInfo.setSettingTagName(settingTagName);
            sheetInfo.setSettingTagNameCell(tagCell);
            sheetInfo.setSheetName(sheetName);
            sheetInfo.setSheetNameCell(sheetNameCell);
            sheetInfo.setLogicalNameRowNum(logicalRowNum);
            sheetInfo.setLogicalNameRowNumCell(logicalRowNumCell);
            sheetInfo.setValueRowNum(valueRowNum);
            sheetInfo.setValueRowNumCell(valueRowNumCell);

            sheetInfoList.add(sheetInfo);
        }
    }

    return sheetInfoList;
}

From source file:org.bbreak.excella.trans.tag.sheet2java.SheetToJavaSettingParser.java

License:Open Source License

/**
 * ?/*from  w w w . jav a 2  s  .co  m*/
 * 
 * @param sheet 
 * @param tagCell ???
 * @param data TransProcessor?processBook, processSheet?<BR> 
 *              ????TagParser.parse??????<BR>
 * @return ?
 * @throws ParseException 
 */
@Override
public List<SheetToJavaSettingInfo> parse(Sheet sheet, Cell tagCell, Object data) throws ParseException {

    // ?
    int tagRowIdx = tagCell.getRowIndex();
    int tagColIdx = tagCell.getColumnIndex();

    // 
    int valueRowFromIdx;
    int valueRowToIdx = sheet.getLastRowNum();

    try {
        Map<String, String> paramDef = TagUtil.getParams(tagCell.getStringCellValue());

        // ?
        valueRowFromIdx = TagUtil.adjustValue(tagRowIdx, paramDef, PARAM_DATA_ROW_FROM,
                DEFAULT_DATA_ROW_FROM_ADJUST);
        if (valueRowFromIdx < 0 || valueRowFromIdx > sheet.getLastRowNum()) {
            throw new ParseException(tagCell, "?" + PARAM_DATA_ROW_FROM);
        }

        // ?
        valueRowToIdx = TagUtil.adjustValue(tagRowIdx, paramDef, PARAM_DATA_ROW_TO, valueRowToIdx - tagRowIdx);
        if (valueRowToIdx > sheet.getLastRowNum() || valueRowToIdx < 0) {
            throw new ParseException(tagCell, "?" + PARAM_DATA_ROW_TO);
        }

        // ???
        if (valueRowFromIdx > valueRowToIdx) {
            throw new ParseException(tagCell,
                    "?" + PARAM_DATA_ROW_FROM + "," + PARAM_DATA_ROW_TO);
        }

    } catch (Exception e) {
        if (e instanceof ParseException) {
            throw (ParseException) e;
        } else {
            throw new ParseException(tagCell, e);
        }
    }

    List<SheetToJavaSettingInfo> sheetSettingInfoList = new ArrayList<SheetToJavaSettingInfo>();

    // ??
    int sheetNameColIdx = tagColIdx++;
    // 
    int valueColIdx = tagColIdx++;
    // 
    int classColIdx = tagColIdx++;
    // 
    int propertyNameColIdx = tagColIdx++;
    // ?
    int uniqueColIdx = tagColIdx++;

    // ?????
    Workbook workbook = sheet.getWorkbook();

    // ???
    for (int rowNum = valueRowFromIdx; rowNum <= valueRowToIdx; rowNum++) {
        Row row = sheet.getRow(rowNum);
        if (row != null) {
            // ??
            Cell sheetNameCell = row.getCell(sheetNameColIdx);
            Cell valueCell = row.getCell(valueColIdx);
            Cell classCell = row.getCell(classColIdx);
            Cell propertyNameCell = row.getCell(propertyNameColIdx);
            Cell uniqueCell = row.getCell(uniqueColIdx);

            // ?
            if ((sheetNameCell == null) && (valueCell == null) && (classCell == null)
                    && (propertyNameCell == null) && (uniqueCell == null)) {
                // ????null??
                continue;

            } else if ((sheetNameCell == null) || (sheetNameCell.getStringCellValue() == null)
                    || ("".equals(sheetNameCell.getStringCellValue()))) {
                // ?????????
                continue;

            } else {
                // ????
                Cell requiredErrorCell = null;
                if (classCell == null) {
                    // ?null??
                    requiredErrorCell = row.createCell(classColIdx);
                }

                // ??
                if (requiredErrorCell != null) {
                    throw new ParseException(requiredErrorCell, "?null??");
                }
            }

            // ??
            SheetToJavaSettingInfo settingInfo = new SheetToJavaSettingInfo();

            // ????
            String sheetName = sheetNameCell.getStringCellValue();
            if (workbook.getSheet(sheetName) == null) {
                throw new ParseException(sheetNameCell, "[" + sheetName + "]????");
            }

            // ??
            settingInfo.setSheetName(sheetName);
            settingInfo.setSheetNameCell(sheetNameCell);

            // ?
            try {
                settingInfo.setClazz(Class.forName(classCell.getStringCellValue()));
                settingInfo.setClazzCell(classCell);
            } catch (ClassNotFoundException e) {
                throw new ParseException(classCell, e);
            }

            // 
            Object value = PoiUtil.getCellValue(valueCell);
            settingInfo.setValueCell(valueCell);

            // ?????
            boolean isValueTag = false;
            // ????????
            boolean isValueLogicalNameTag = false;
            if (value instanceof String) {
                // ??
                String valueStr = (String) value;
                if ((valueStr).startsWith(SheetToJavaExecuter.TAG_PREFIX)) {
                    // ??
                    isValueTag = true;
                    if ((valueStr).startsWith(SheetToJavaExecuter.TAG_LOGICAL_NAME_PREFIX)) {
                        // ?????
                        isValueLogicalNameTag = true;
                    }
                }
            }

            if (!isValueTag || isValueLogicalNameTag) {
                // ?????????

                // ??
                Cell requiredErrorCell = null;
                if (propertyNameCell == null) {
                    requiredErrorCell = row.createCell(propertyNameColIdx);
                }
                if (requiredErrorCell != null) {
                    throw new ParseException(requiredErrorCell, "?null??");
                }

                // ?
                settingInfo.setPropertyName(propertyNameCell.getStringCellValue());
                settingInfo.setPropertyNameCell(propertyNameCell);

                // ?
                Class<?> propertyClass = null;
                try {
                    Object obj = settingInfo.getClazz().newInstance();
                    propertyClass = PropertyUtils.getPropertyType(obj, settingInfo.getPropertyName());
                } catch (Exception e) {
                    throw new ParseException(propertyNameCell, e);
                }
                if (propertyClass == null) {
                    throw new ParseException(propertyNameCell,
                            "?:" + settingInfo.getPropertyName());
                }

                // ????
                if (uniqueCell != null) {
                    if (uniqueCell.getStringCellValue() != null
                            && uniqueCell.getStringCellValue().equals(UNIQUE_PROPERTY_MARK)) {
                        settingInfo.setUnique(true);
                        settingInfo.setUniqueCell(uniqueCell);
                    }
                }
            } else {
                // ??

                // ?????
                try {
                    TagUtil.getParams((String) value);
                } catch (Exception e) {
                    throw new ParseException(valueCell, e);
                }
            }

            // ??????
            boolean checkTypeFlag = false;
            if (value instanceof String) {
                if (!isValueTag) {
                    // ??
                    checkTypeFlag = true;
                }
            } else {
                // ??
                if (value != null) {
                    // null??
                    checkTypeFlag = true;
                }
            }

            // ?
            if (checkTypeFlag) {
                // ????
                Object obj;
                try {
                    obj = settingInfo.getClazz().newInstance();
                    Class<?> propertyClass = PropertyUtils.getPropertyType(obj, settingInfo.getPropertyName());
                    value = PoiUtil.getCellValue(valueCell, propertyClass);
                } catch (Exception e) {
                    throw new ParseException(valueCell, e);
                }
            }
            settingInfo.setValue(value);

            // ????
            sheetSettingInfoList.add(settingInfo);
        }
    }
    return sheetSettingInfoList;
}

From source file:org.bbreak.excella.trans.tag.sheet2sql.SheetToSqlParser.java

License:Open Source License

/**
 * ?//from   w w  w  .  j  a v  a 2 s.c o m
 * 
 * @param sheet 
 * @param tagCell ???
 * @param data TransProcessor?processBook, processSheet?<BR> 
 *              ????TagParser.parse??????<BR>
 * @return ?
 * @throws ParseException 
 */
@Override
public List<SheetToSqlParseInfo> parse(Sheet sheet, Cell tagCell, Object data) throws ParseException {

    // ?
    int tagRowIdx = tagCell.getRowIndex();
    int tagColIdx = tagCell.getColumnIndex();

    int valueRowFromIdx;
    int valueRowToIdx = sheet.getLastRowNum();

    // ????
    String settingTagName = getTag() + DEFAULT_SETTING_SUFFIX;

    try {
        Map<String, String> paramDef = TagUtil.getParams(tagCell.getStringCellValue());

        // ?
        valueRowFromIdx = TagUtil.adjustValue(tagRowIdx, paramDef, PARAM_DATA_ROW_FROM,
                DEFAULT_DATA_ROW_FROM_ADJUST);
        if (valueRowFromIdx < 0 || valueRowFromIdx > sheet.getLastRowNum()) {
            throw new ParseException(tagCell, "?" + PARAM_DATA_ROW_FROM);
        }

        // ?
        valueRowToIdx = TagUtil.adjustValue(tagRowIdx, paramDef, PARAM_DATA_ROW_TO, valueRowToIdx - tagRowIdx);
        if (valueRowToIdx > sheet.getLastRowNum() || valueRowToIdx < 0) {
            throw new ParseException(tagCell, "?" + PARAM_DATA_ROW_TO);
        }

        // ???
        if (valueRowFromIdx > valueRowToIdx) {
            throw new ParseException(tagCell,
                    "?" + PARAM_DATA_ROW_FROM + "," + PARAM_DATA_ROW_TO);
        }

        // ????
        if (paramDef.containsKey(PARAM_SETTING_TAG_NAME)) {
            settingTagName = paramDef.get(PARAM_SETTING_TAG_NAME);
        }

        // ?
        if (paramDef.containsKey(PARAM_RESULT_KEY)) {
            // ???????
            throw new ParseException(tagCell, PARAM_RESULT_KEY + "????????");
        }

    } catch (Exception e) {
        if (e instanceof ParseException) {
            throw (ParseException) e;
        } else {
            throw new ParseException(tagCell, e);
        }
    }

    List<SheetToSqlParseInfo> sheetInfoList = new ArrayList<SheetToSqlParseInfo>();

    // ??
    int sheetNameColIdx = tagColIdx++;
    // ???No
    int logicalRowColIdx = tagColIdx++;
    // No
    int dataRowColIdx = tagColIdx;

    // ?????
    Workbook workbook = sheet.getWorkbook();

    // ???
    for (int rowNum = valueRowFromIdx; rowNum <= valueRowToIdx; rowNum++) {
        Row row = sheet.getRow(rowNum);
        if (row != null) {
            // ??
            Cell sheetNameCell = row.getCell(sheetNameColIdx);
            Cell logicalRowNumCell = row.getCell(logicalRowColIdx);
            Cell valueRowNumCell = row.getCell(dataRowColIdx);

            // ?
            if ((sheetNameCell == null) && (logicalRowNumCell == null) && (valueRowNumCell == null)) {
                // ????null??
                continue;

            } else if ((sheetNameCell == null) || (sheetNameCell.getStringCellValue() == null)
                    || ("".equals(sheetNameCell.getStringCellValue()))) {
                // ?????????
                continue;

            } else {
                // ????
                Cell requiredErrorCell = null;
                if (logicalRowNumCell == null) {
                    requiredErrorCell = row.createCell(logicalRowColIdx);
                } else if (valueRowNumCell == null) {
                    requiredErrorCell = row.createCell(dataRowColIdx);
                }

                // ??????
                if (requiredErrorCell != null) {
                    throw new ParseException(requiredErrorCell, "?null??");
                }
            }

            // ???No?
            int logicalRowNum;
            try {
                logicalRowNum = (Integer) PoiUtil.getCellValue(logicalRowNumCell, Integer.class);
            } catch (Exception e) {
                throw new ParseException(logicalRowNumCell, e);
            }

            // No?
            int valueRowNum;
            try {
                valueRowNum = (Integer) PoiUtil.getCellValue(valueRowNumCell, Integer.class);
            } catch (Exception e) {
                throw new ParseException(valueRowNumCell, e);
            }

            // ???
            String sheetName = sheetNameCell.getStringCellValue();
            if (workbook.getSheet(sheetName) == null) {
                throw new ParseException(sheetNameCell, "[" + sheetName + "]????");
            }

            // 
            SheetToSqlParseInfo sheetInfo = new SheetToSqlParseInfo();
            sheetInfo.setSettingTagName(settingTagName);
            sheetInfo.setSheetName(sheetName);
            sheetInfo.setLogicalNameRowNum(logicalRowNum);
            sheetInfo.setValueRowNum(valueRowNum);

            sheetInfoList.add(sheetInfo);
        }
    }

    return sheetInfoList;
}

From source file:org.bbreak.excella.trans.tag.sheet2sql.SheetToSqlSettingParser.java

License:Open Source License

/**
 * ?// w ww . j  a v  a  2  s  .  com
 * 
 * @param sheet 
 * @param tagCell ???
 * @param data TransProcessor?processBook, processSheet?<BR>
 *              ????TagParser.parse??????<BR>
 * @return ?
 * @throws ParseException 
 */
@Override
public List<SheetToSqlSettingInfo> parse(Sheet sheet, Cell tagCell, Object data) throws ParseException {

    // ?
    int tagRowIdx = tagCell.getRowIndex();
    int tagColIdx = tagCell.getColumnIndex();

    // 
    int valueRowFromIdx;
    int valueRowToIdx = sheet.getLastRowNum();

    try {
        Map<String, String> paramDef = TagUtil.getParams(tagCell.getStringCellValue());

        // ?
        valueRowFromIdx = TagUtil.adjustValue(tagRowIdx, paramDef, PARAM_DATA_ROW_FROM,
                DEFAULT_DATA_ROW_FROM_ADJUST);
        if (valueRowFromIdx < 0 || valueRowFromIdx > sheet.getLastRowNum()) {
            throw new ParseException(tagCell, "?" + PARAM_DATA_ROW_TO);
        }

        // ?
        valueRowToIdx = TagUtil.adjustValue(tagRowIdx, paramDef, PARAM_DATA_ROW_TO, valueRowToIdx - tagRowIdx);
        if (valueRowToIdx > sheet.getLastRowNum() || valueRowToIdx < 0) {
            throw new ParseException(tagCell, "?" + PARAM_DATA_ROW_TO);
        }

        // ???
        if (valueRowFromIdx > valueRowToIdx) {
            throw new ParseException(tagCell,
                    "?" + PARAM_DATA_ROW_FROM + "," + PARAM_DATA_ROW_TO);
        }

    } catch (Exception e) {
        if (e instanceof ParseException) {
            throw (ParseException) e;
        } else {
            throw new ParseException(tagCell, e);
        }
    }

    List<SheetToSqlSettingInfo> sheetSettingInfoList = new ArrayList<SheetToSqlSettingInfo>();

    // ??
    int sheetNameColIdx = tagColIdx++;
    // 
    int valueColIdx = tagColIdx++;
    // 
    int tableColIdx = tagColIdx++;
    // 
    int columnNameColIdx = tagColIdx++;
    // ???
    int uniqueColIdx = tagColIdx++;
    // 
    int dataTypeColIdx = tagColIdx++;

    // ?????
    Workbook workbook = sheet.getWorkbook();

    // ???
    for (int rowNum = valueRowFromIdx; rowNum <= valueRowToIdx; rowNum++) {
        Row row = sheet.getRow(rowNum);
        if (row != null) {
            // ??
            Cell sheetNameCell = row.getCell(sheetNameColIdx);
            Cell valueCell = row.getCell(valueColIdx);
            Cell tableNameCell = row.getCell(tableColIdx);
            Cell columnNameCell = row.getCell(columnNameColIdx);
            Cell uniqueCell = row.getCell(uniqueColIdx);
            Cell dataTypeCell = row.getCell(dataTypeColIdx);

            // ?
            if ((sheetNameCell == null) && (valueCell == null) && (tableNameCell == null)
                    && (columnNameCell == null) && (uniqueCell == null) && (dataTypeCell == null)) {
                // ????null??
                continue;

            } else if ((sheetNameCell == null) || (sheetNameCell.getStringCellValue() == null)
                    || ("".equals(sheetNameCell.getStringCellValue()))) {
                // ?????????
                continue;

            } else {
                // ????
                Cell requiredErrorCell = null;
                if (tableNameCell == null) {
                    // ?null??
                    requiredErrorCell = row.createCell(tableColIdx);
                } else if (columnNameCell == null) {
                    // ?null??
                    requiredErrorCell = row.createCell(columnNameColIdx);
                }

                if (requiredErrorCell != null) {
                    // ??
                    throw new ParseException(requiredErrorCell, "?null??");
                }
            }

            // ??
            SheetToSqlSettingInfo settingInfo = new SheetToSqlSettingInfo();

            // ????
            String sheetName = sheetNameCell.getStringCellValue();
            if (workbook.getSheet(sheetName) == null) {
                throw new ParseException(sheetNameCell, "[" + sheetName + "]????");
            }

            // ??
            settingInfo.setSheetName(sheetName);
            settingInfo.setSheetNameCell(sheetNameCell);

            // ??
            settingInfo.setTableName(tableNameCell.getStringCellValue());
            settingInfo.setTableNameCell(tableNameCell);

            // 
            settingInfo.setColumnName(columnNameCell.getStringCellValue());
            settingInfo.setColumnNameCell(columnNameCell);

            // 
            if (valueCell != null) {
                Object value = PoiUtil.getCellValue(valueCell);
                settingInfo.setValue(value);
                settingInfo.setValueCell(valueCell);
            }

            // ???
            if (uniqueCell != null) {
                if (uniqueCell.getStringCellValue() != null
                        && uniqueCell.getStringCellValue().equals(UNIQUE_PROPERTY_MARK)) {
                    settingInfo.setUnique(true);
                    settingInfo.setUniqueCell(uniqueCell);
                }
            }

            // 
            if (dataTypeCell != null) {
                settingInfo.setDataType(dataTypeCell.getStringCellValue());
                settingInfo.setDataTypeCell(dataTypeCell);
            }

            // ????
            sheetSettingInfoList.add(settingInfo);
        }
    }
    return sheetSettingInfoList;
}

From source file:org.codelabor.example.crud.emp.web.controller.EmpController.java

License:Apache License

private List<EmpDto> fileToDtoList(MultipartFile file, List<String> failureMessages)
        throws IllegalArgumentException, InvalidFormatException, IOException { // NOPMD
    // by/*from  w ww . j  a  v  a 2s .  com*/
    // "SHIN Sang-jae"

    Workbook wb = WorkbookFactory.create(file.getInputStream());
    int numberOfSheets = wb.getNumberOfSheets();
    logger.debug("numberOfSheets: {}", numberOfSheets);

    // prepare model
    List<EmpDto> empDtoList = new ArrayList<EmpDto>();

    // set effective position
    int effectiveFirstSheetIndex = 0;
    int effectiveLastSheetIndex = numberOfSheets - 1;

    // traverse sheet
    StringBuilder sb = new StringBuilder();
    for (int i = effectiveFirstSheetIndex; i <= effectiveLastSheetIndex; i++) {
        Sheet sheet = wb.getSheetAt(i);
        String sheetName = sheet.getSheetName();
        logger.debug("sheetName: {}", sheetName);
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();
        logger.debug("firstRowNum: {},  lastRowNum: {}", firstRowNum, lastRowNum);

        // set effective position
        int effectiveFirstRowIndex = 1; // header row: 0
        int effectiveLastRowIndex = lastRowNum;

        // traverse row
        for (int j = effectiveFirstRowIndex; j <= effectiveLastRowIndex; j++) {
            // prepare model
            EmpDto empDto = new EmpDto(); // NOPMD by "SHIN Sang-jae"

            Row row = sheet.getRow(j);
            int rowNum = row.getRowNum();
            int firstCellNum = row.getFirstCellNum();
            int lastCellNum = row.getLastCellNum();
            logger.debug("rowNum: {}, firstCellNum: {},  lastCellNum: {}", rowNum, firstCellNum, lastCellNum);

            // set effective position
            int effectiveFirstCellIndex = firstCellNum;
            int effectiveLastCellIndex = lastCellNum - 1;

            // traverse cell
            for (int k = effectiveFirstCellIndex; k <= effectiveLastCellIndex; k++) {
                Cell cell = row.getCell(k);
                if (cell != null) {
                    int rowIndex = cell.getRowIndex();
                    int columnIndex = cell.getColumnIndex();
                    CellReference cellRef = new CellReference(rowIndex, columnIndex); // NOPMD by "SHIN Sang-jae"

                    logger.debug("cellRef: {}, rowIndex: {}, columnIndex: {}", cellRef, rowIndex, columnIndex);
                    // populate dto
                    switch (k) {
                    case 0: // EMPNO
                        empDto.setEmpNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 1: // ENAME
                        empDto.setEname(cell.getRichStringCellValue().toString());
                        break;
                    case 2: // JOB
                        empDto.setJob(cell.getRichStringCellValue().toString());
                        break;
                    case 3: // MGR
                        empDto.setMgr(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 4: // HIREDATE
                        empDto.setHireDate(cell.getDateCellValue());
                        break;
                    case 5: // SAL
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setSal(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 6: // COMM
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setComm(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 7: // DEPTNO
                        empDto.setDeptNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    default:
                        break;
                    }
                }
            }
            logger.debug("empDto: {}", empDto);

            // validate
            Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
            Set<ConstraintViolation<EmpDto>> violations = validator.validate(empDto);

            if (violations.isEmpty()) {
                // do all or nothing
                empDtoList.add(empDto);
            } else {
                // add failure message
                sb.setLength(0); // init StringBuilder for reuse
                for (ConstraintViolation<EmpDto> violation : violations) {
                    String propertyPath = violation.getPropertyPath().toString();
                    String message = violation.getMessage();
                    sb.append(message);
                    sb.append(" (row: ").append(j).append(", property: ").append(propertyPath).append(')');
                    failureMessages.add(sb.toString());
                    logger.error(sb.toString());
                    sb.setLength(0);
                }
            }
        }
    }
    return empDtoList;
}

From source file:org.codelabor.example.crud.emp.web.controller.EmpController.java

License:Apache License

private List<EmpDto> fileToDtoList(Part file, List<String> failureMessages)
        throws IllegalArgumentException, InvalidFormatException, IOException { // NOPMD
    // by//  ww  w .j a  v  a  2s .c om
    // "SHIN Sang-jae"

    Workbook wb = WorkbookFactory.create(file.getInputStream());
    int numberOfSheets = wb.getNumberOfSheets();
    logger.debug("numberOfSheets: {}", numberOfSheets);

    // prepare model
    List<EmpDto> empDtoList = new ArrayList<EmpDto>();

    // set effective position
    int effectiveFirstSheetIndex = 0;
    int effectiveLastSheetIndex = numberOfSheets - 1;

    // traverse sheet
    StringBuilder sb = new StringBuilder();
    for (int i = effectiveFirstSheetIndex; i <= effectiveLastSheetIndex; i++) {
        Sheet sheet = wb.getSheetAt(i);
        String sheetName = sheet.getSheetName();
        logger.debug("sheetName: {}", sheetName);
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();
        logger.debug("firstRowNum: {},  lastRowNum: {}", firstRowNum, lastRowNum);

        // set effective position
        int effectiveFirstRowIndex = 1; // header row: 0
        int effectiveLastRowIndex = lastRowNum;

        // traverse row
        for (int j = effectiveFirstRowIndex; j <= effectiveLastRowIndex; j++) {
            // prepare model
            EmpDto empDto = new EmpDto(); // NOPMD by "SHIN Sang-jae"

            Row row = sheet.getRow(j);
            int rowNum = row.getRowNum();
            int firstCellNum = row.getFirstCellNum();
            int lastCellNum = row.getLastCellNum();
            logger.debug("rowNum: {}, firstCellNum: {},  lastCellNum: {}", rowNum, firstCellNum, lastCellNum);

            // set effective position
            int effectiveFirstCellIndex = firstCellNum;
            int effectiveLastCellIndex = lastCellNum - 1;

            // traverse cell
            for (int k = effectiveFirstCellIndex; k <= effectiveLastCellIndex; k++) {
                Cell cell = row.getCell(k);
                if (cell != null) {
                    int rowIndex = cell.getRowIndex();
                    int columnIndex = cell.getColumnIndex();
                    CellReference cellRef = new CellReference(rowIndex, columnIndex); // NOPMD by "SHIN Sang-jae"

                    logger.debug("cellRef: {}, rowIndex: {}, columnIndex: {}", cellRef, rowIndex, columnIndex);
                    // populate dto
                    switch (k) {
                    case 0: // EMPNO
                        empDto.setEmpNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 1: // ENAME
                        empDto.setEname(cell.getRichStringCellValue().toString());
                        break;
                    case 2: // JOB
                        empDto.setJob(cell.getRichStringCellValue().toString());
                        break;
                    case 3: // MGR
                        empDto.setMgr(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    case 4: // HIREDATE
                        empDto.setHireDate(cell.getDateCellValue());
                        break;
                    case 5: // SAL
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setSal(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 6: // COMM
                        // http://stackoverflow.com/questions/12395281/convert-double-to-bigdecimal-and-set-bigdecimal-precision
                        empDto.setComm(BigDecimal.valueOf(cell.getNumericCellValue()));
                        break;
                    case 7: // DEPTNO
                        empDto.setDeptNo(((Double) cell.getNumericCellValue()).intValue());
                        break;
                    default:
                        break;
                    }
                }
            }
            logger.debug("empDto: {}", empDto);

            // validate
            Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
            Set<ConstraintViolation<EmpDto>> violations = validator.validate(empDto);

            if (violations.isEmpty()) {
                // do all or nothing
                empDtoList.add(empDto);
            } else {
                // add failure message
                sb.setLength(0); // init StringBuilder for reuse
                for (ConstraintViolation<EmpDto> violation : violations) {
                    String propertyPath = violation.getPropertyPath().toString();
                    String message = violation.getMessage();
                    sb.append(message);
                    sb.append(" (row: ").append(j).append(", property: ").append(propertyPath).append(')');
                    failureMessages.add(sb.toString());
                    logger.error(sb.toString());
                    sb.setLength(0);
                }
            }
        }
    }
    return empDtoList;
}