Example usage for org.apache.poi.ss.usermodel Workbook getSheetName

List of usage examples for org.apache.poi.ss.usermodel Workbook getSheetName

Introduction

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

Prototype

String getSheetName(int sheet);

Source Link

Document

Get the sheet name

Usage

From source file:org.bbreak.excella.reports.listener.RemoveAdapterTest.java

License:Open Source License

/**
 * {@link org.bbreak.excella.reports.listener.RemoveAdapter#postParse(org.apache.poi.ss.usermodel.Sheet, org.bbreak.excella.core.SheetParser, org.bbreak.excella.core.SheetData)} ????
 *//*w  ww . j  a v  a  2  s  . c o m*/
@Test
public void testPostParse() {

    Workbook workbook = getWorkbook();

    RemoveAdapter adapter = new RemoveAdapter();

    SheetParser sheetParser = new SheetParser();
    List<ReportsTagParser<?>> reportParsers = new ArrayList<ReportsTagParser<?>>(
            ReportCreateHelper.createDefaultParsers().values());

    for (ReportsTagParser<?> parser : reportParsers) {
        sheetParser.addTagParser(parser);
    }

    Sheet sheet = workbook.getSheetAt(0);
    try {
        adapter.postParse(sheet, sheetParser, null);
    } catch (ParseException e) {
        e.printStackTrace();
        fail();
    }
    checkSheet(workbook.getSheetName(0), sheet, true);

    workbook = getWorkbook();
    sheet = workbook.getSheetAt(1);
    try {
        adapter.postParse(sheet, sheetParser, null);
    } catch (ParseException e) {
        e.printStackTrace();
        fail();
    }
    checkSheet(workbook.getSheetName(1), sheet, true);

}

From source file:org.bbreak.excella.reports.ReportsTestUtil.java

License:Open Source License

/**
 * /*from   w  w  w . j  a  v  a2s  .  c o m*/
 * 
 * @param expected 
 * @param actual 
 * @param isActCopyOfExp ??????true
 * @throws ReportsCheckException 
 */
public static void checkSheet(Sheet expected, Sheet actual, boolean isActCopyOfExp)
        throws ReportsCheckException {

    List<CheckMessage> errors = new ArrayList<CheckMessage>();

    Workbook expectedWorkbook = expected.getWorkbook();
    Workbook actualWorkbook = actual.getWorkbook();

    if (log.isDebugEnabled()) {
        log.debug("[" + actualWorkbook.getSheetName(actualWorkbook.getSheetIndex(actual))
                + "] check start!");
    }

    // ----------------------
    // ????
    // ----------------------
    // ??
    String eSheetName = expectedWorkbook.getSheetName(expectedWorkbook.getSheetIndex(expected));
    String aSheetName = actualWorkbook.getSheetName(actualWorkbook.getSheetIndex(actual));

    if (!isActCopyOfExp) {
        if (!eSheetName.equals(aSheetName)) {
            errors.add(new CheckMessage("??", eSheetName, aSheetName));
        }
    }

    // ?
    String ePrintSetupString = getPrintSetupString(expected.getPrintSetup());
    String aPrintSetupString = getPrintSetupString(actual.getPrintSetup());

    if (!ePrintSetupString.equals(aPrintSetupString)) {
        errors.add(new CheckMessage("?", ePrintSetupString, aPrintSetupString));
    }

    // ?
    String eHeaderString = getHeaderString(expected.getHeader());
    String aHeaderString = getHeaderString(actual.getHeader());
    if (!eHeaderString.equals(aHeaderString)) {
        errors.add(new CheckMessage("", eHeaderString, aHeaderString));
    }
    String eFooterString = getFooterString(expected.getFooter());
    String aFooterString = getFooterString(actual.getFooter());
    if (!eFooterString.equals(aFooterString)) {
        errors.add(new CheckMessage("", eFooterString, aFooterString));
    }

    // 
    String eBreaksString = getBreaksString(expected);
    String aBreaksString = getBreaksString(actual);
    log.debug(eBreaksString + "/" + aBreaksString);
    if (!eBreaksString.equals(aBreaksString)) {
        errors.add(new CheckMessage("", eBreaksString, aBreaksString));
    }

    // ?
    String expectedPrintArea = expectedWorkbook.getPrintArea(expectedWorkbook.getSheetIndex(expected));
    String actualPrintArea = actualWorkbook.getPrintArea(actualWorkbook.getSheetIndex(actual));
    if (expectedPrintArea != null || actualPrintArea != null) {
        // ????????Null?????????????
        // if ( expectedPrintArea == null || actualPrintArea == null || !equalPrintArea( expectedPrintArea, actualPrintArea, isActCopyOfExp)) {
        // errors.add( new CheckMessage( "?", expectedPrintArea, actualPrintArea));
        // }
        if (!isActCopyOfExp) {
            if (expectedPrintArea == null || actualPrintArea == null
                    || !expectedPrintArea.equals(actualPrintArea)) {
                errors.add(new CheckMessage("?", expectedPrintArea, actualPrintArea));
            }
        }
    }

    // (?)
    String ePaneInformationString = getPaneInformationString(expected.getPaneInformation());
    String aPaneInformationString = getPaneInformationString(actual.getPaneInformation());

    if (!ePaneInformationString.equals(aPaneInformationString)) {
        errors.add(new CheckMessage("(?)", expectedPrintArea, actualPrintArea));
    }

    // ??????

    // ?????

    // ?????

    // 

    // 
    if (expected.isDisplayGridlines() ^ actual.isDisplayGridlines()) {
        errors.add(new CheckMessage("",
                String.valueOf(expected.isDisplayGridlines()), String.valueOf(actual.isDisplayGridlines())));
    }

    // ?
    if (expected.isDisplayRowColHeadings() ^ actual.isDisplayRowColHeadings()) {
        errors.add(new CheckMessage("?", String.valueOf(expected.isDisplayRowColHeadings()),
                String.valueOf(actual.isDisplayRowColHeadings())));
    }

    // ?
    if (expected.isDisplayFormulas() ^ actual.isDisplayFormulas()) {
        errors.add(new CheckMessage("?", String.valueOf(expected.isDisplayFormulas()),
                String.valueOf(actual.isDisplayFormulas())));
    }
    // ??
    if (expected.getNumMergedRegions() != actual.getNumMergedRegions()) {
        errors.add(new CheckMessage("??", String.valueOf(expected.getNumMergedRegions()),
                String.valueOf(actual.getNumMergedRegions())));
    }

    for (int i = 0; i < actual.getNumMergedRegions(); i++) {

        CellRangeAddress actualAddress = null;
        if (expected instanceof HSSFSheet) {
            actualAddress = ((HSSFSheet) actual).getMergedRegion(i);
        } else if (expected instanceof XSSFSheet) {
            actualAddress = ((XSSFSheet) actual).getMergedRegion(i);
        }

        StringBuffer expectedAdressBuffer = new StringBuffer();
        boolean equalAddress = false;
        for (int j = 0; j < expected.getNumMergedRegions(); j++) {
            CellRangeAddress expectedAddress = null;
            if (expected instanceof HSSFSheet) {
                expectedAddress = ((HSSFSheet) expected).getMergedRegion(j);
            } else if (expected instanceof XSSFSheet) {
                expectedAddress = ((XSSFSheet) expected).getMergedRegion(j);
            }
            if (expectedAddress.toString().equals(actualAddress.toString())) {
                equalAddress = true;
                break;
            }
            CellReference crA = new CellReference(expectedAddress.getFirstRow(),
                    expectedAddress.getFirstColumn());
            CellReference crB = new CellReference(expectedAddress.getLastRow(),
                    expectedAddress.getLastColumn());
            expectedAdressBuffer.append(" [" + crA.formatAsString() + ":" + crB.formatAsString() + "]");
        }

        if (!equalAddress) {
            errors.add(new CheckMessage("??", expectedAdressBuffer.toString(),
                    actualAddress.toString()));
        }

    }

    int maxColumnNum = -1;
    if (expected instanceof HSSFSheet) {
        maxColumnNum = HSSF_MAX_COLUMN_NUMBER;
    } else if (expected instanceof XSSFSheet) {
        maxColumnNum = XSSF_MAX_COLUMN_NUMBER;
    }
    for (int i = 0; i < maxColumnNum; i++) {
        try {
            // 
            checkCellStyle(expected.getWorkbook(), expected.getColumnStyle(i), actual.getWorkbook(),
                    actual.getColumnStyle(i));
        } catch (ReportsCheckException e) {
            CheckMessage checkMessage = e.getCheckMessages().iterator().next();
            checkMessage.setMessage("[" + i + "]" + checkMessage.getMessage());
            errors.add(checkMessage);
        }

        // 
        if (expected.getColumnWidth(i) != actual.getColumnWidth(i)) {
            errors.add(new CheckMessage("[" + i + "]", String.valueOf(expected.getColumnWidth(i)),
                    String.valueOf(actual.getColumnWidth(i))));
        }
    }

    // ???
    if (expected.getLastRowNum() != actual.getLastRowNum()) {
        // ??????
        if (expected.getLastRowNum() < actual.getLastRowNum()) {
            int lastRowIndex = -1;
            if (expected instanceof HSSFSheet) {
                lastRowIndex = 0;
            }
            Iterator<Row> rowIterator = actual.rowIterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                // ?????
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (cell.getCellTypeEnum() != CellType.BLANK) {
                        lastRowIndex = row.getRowNum();
                        break;
                    }
                }
            }
            if (expected.getLastRowNum() != lastRowIndex) {
                errors.add(new CheckMessage("", String.valueOf(expected.getLastRowNum()),
                        String.valueOf(lastRowIndex)));
            }
        } else {
            errors.add(new CheckMessage("", String.valueOf(expected.getLastRowNum()),
                    String.valueOf(actual.getLastRowNum())));
        }

    }

    if (errors.isEmpty()) {
        for (int i = 0; i <= expected.getLastRowNum(); i++) {
            try {
                checkRow(expected.getRow(i), actual.getRow(i));
            } catch (ReportsCheckException e) {
                errors.addAll(e.getCheckMessages());
            }
        }
    }

    if (!errors.isEmpty()) {
        if (log.isErrorEnabled()) {
            for (CheckMessage message : errors) {
                log.error("?[" + message.getMessage() + "]");
                log.error(":" + message.getExpected());
                log.error(":" + message.getActual());
            }
        }
        throw new ReportsCheckException(errors);
    }

    if (log.isDebugEnabled()) {
        log.debug("[" + actualWorkbook.getSheetName(actualWorkbook.getSheetIndex(actual))
                + "] check end.");
    }

}

From source file:org.bbreak.excella.reports.tag.ColRepeatParamParser.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   ww  w  .  j  ava  2  s. c o  m
    checkParam(paramDef, tagCell);

    String tag = tagCell.getStringCellValue();
    ReportsParserInfo info = (ReportsParserInfo) data;
    ParamInfo paramInfo = info.getParamInfo();
    ParsedReportInfo parsedReportInfo = new ParsedReportInfo();

    // ??
    Object[] paramValues = null;
    try {
        // ???
        String replaceParam = paramDef.get(PARAM_VALUE);

        // ?
        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);
        }

        // ???
        boolean hideDuplicate = false;
        if (paramDef.containsKey(PARAM_DUPLICATE)) {
            hideDuplicate = Boolean.valueOf(paramDef.get(PARAM_DUPLICATE));
        }

        // 
        if (ReportsUtil.VALUE_SHEET_NAMES.equals(replaceParam)) {
            // ??
            paramValues = ReportsUtil.getSheetNames(info.getReportBook()).toArray();
        } else if (ReportsUtil.VALUE_SHEET_VALUES.equals(replaceParam)) {
            // 
            paramValues = ReportsUtil
                    .getSheetValues(info.getReportBook(), propertyName, info.getReportParsers()).toArray();
        } else {
            // ???
            if (paramInfo != null) {
                paramValues = getParamData(paramInfo, replaceParam);
            }
        }

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

        // ?
        if (hideDuplicate && paramValues.length > 1) {
            List<Object> paramValuesList = new ArrayList<Object>();
            for (int i = 0; i <= paramValues.length - 1; i++) {
                // ?????
                if (!paramValuesList.contains(paramValues[i])) {
                    paramValuesList.add(paramValues[i]);
                } else {
                    paramValuesList.add(null);
                }
            }
            paramValues = paramValuesList.toArray();
        }

        // ?
        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 unitColSize = 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()) {
                    // ????????????
                    // ??????
                    unitColSize = curMergedAdress.getLastColumn() - curMergedAdress.getFirstColumn() + 1;

                    // ??????
                    shiftNum = shiftNum * unitColSize;
                }
            }
        }

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

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

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

        // ?            
        if (shiftNum > 1) {
            // ?(????????)
            int shiftColSize = tagCell.getColumnIndex() + shiftNum - unitColSize - 1;
            // ???
            CellRangeAddress rangeAddress = new CellRangeAddress(tagCell.getRowIndex(), tagCell.getRowIndex(),
                    tagCell.getColumnIndex(), shiftColSize);
            PoiUtil.insertRangeRight(sheet, rangeAddress);
            // 
            int tagCellWidth = sheet.getColumnWidth(tagCell.getColumnIndex());
            for (int i = tagCell.getColumnIndex() + 1; i <= shiftColSize; i++) {
                int colWidth = sheet.getColumnWidth(i);
                if (colWidth < tagCellWidth) {
                    // ??  ???????
                    // ??????
                    sheet.setColumnWidth(i, tagCellWidth);
                }
            }
        }

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

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

            // ??????
            // ??0???(?????????)???????
            int cellIndex = colIndex % unitColSize;

            // ?????????
            boolean skipCol = false;
            if (cellIndex != 0) {
                skipCol = 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 (!skipCol && !(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 (!skipCol && 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 (!skipCol && unitColSize > 1 && paramLength > valueIndex + 1) {
                CellRangeAddress rangeAddress = new CellRangeAddress(cell.getRowIndex(), cell.getRowIndex(),
                        cell.getColumnIndex(), cell.getColumnIndex() + unitColSize - 1);
                sheet.addMergedRegion(rangeAddress);

                // ????????????
                beforeValue = value;
            }

            // ???????
            if (unitColSize == 1) {
                beforeValue = value;
            }

        }

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

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

}

From source file:org.bbreak.excella.reports.tag.ImageParamParser.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 va 2s.  c o  m
    if (hasComments(sheet)) {
        throw new ParseException(
                "?[" + sheet.getWorkbook().getSheetName(sheet.getWorkbook().getSheetIndex(sheet))
                        + "]");
    }

    // ?
    checkParam(paramDef, tagCell);

    ReportsParserInfo reportsParserInfo = (ReportsParserInfo) data;

    ParamInfo paramInfo = reportsParserInfo.getParamInfo();

    String paramValue = null;

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

        paramValue = getParamData(paramInfo, replaceParam);

        // ??
        Integer dx1 = null;
        if (paramDef.containsKey(PARAM_WIDTH)) {
            dx1 = Integer.valueOf(paramDef.get(PARAM_WIDTH));
        }

        // ???
        Integer dy1 = null;
        if (paramDef.containsKey(PARAM_HEIGHT)) {
            dy1 = Integer.valueOf(paramDef.get(PARAM_HEIGHT));
        }

        // ???
        Double scale = 1.0;
        if (paramDef.containsKey(PARAM_SCALE)) {
            scale = Double.valueOf(paramDef.get(PARAM_SCALE));
        }

        // ??????
        if (ReportsUtil.getMergedAddress(sheet, tagCell.getRowIndex(), tagCell.getColumnIndex()) != null) {
            CellStyle cellStyle = tagCell.getCellStyle();
            tagCell.setCellType(CellType.BLANK);
            tagCell.setCellStyle(cellStyle);
        } else {
            tagCell = new CellClone(tagCell);
            PoiUtil.clearCell(sheet, new CellRangeAddress(tagCell.getRowIndex(), tagCell.getRowIndex(),
                    tagCell.getColumnIndex(), tagCell.getColumnIndex()));
        }

        if (log.isDebugEnabled()) {
            Workbook workbook = sheet.getWorkbook();
            String sheetName = workbook.getSheetName(workbook.getSheetIndex(sheet));

            log.debug("[??=" + sheetName + ",=(" + tagCell.getRowIndex() + ","
                    + tagCell.getColumnIndex() + ")]  " + tagCell.getStringCellValue() + "  " + paramValue);
        }

        if (paramValue != null) {
            replaceImageValue(sheet, tagCell, paramValue, dx1, dy1, scale);
        }

    }

    // ????
    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.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 ww .j a v a  2s. 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());
    }/*  w ww .  ja va2s.  c o 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.cytoscape.tableimport.internal.ImportNetworkTableReaderTask.java

License:Open Source License

@Override
public void run(TaskMonitor monitor) throws Exception {

    monitor.setTitle("Loading network from table");
    monitor.setProgress(0.0);// w  ww.  j a  va2s  .c o m
    monitor.setStatusMessage("Loading network...");

    Workbook workbook = null;
    // Load Spreadsheet data for preview.
    if (fileType != null && (fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
            || fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) && workbook == null) {
        try {
            workbook = WorkbookFactory.create(is);
        } catch (InvalidFormatException e) {
            //e.printStackTrace();
            throw new IllegalArgumentException("Could not read Excel file.  Maybe the file is broken?", e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    String networkName;

    if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
            || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) {
        Sheet sheet = workbook.getSheetAt(0);
        networkName = workbook.getSheetName(0);

        reader = new ExcelNetworkSheetReader(networkName, sheet, ntmp, this.nMap, this.rootNetwork);
    } else {
        networkName = this.inputName;
        reader = new NetworkTableReader(networkName, this.is, ntmp, this.nMap, this.rootNetwork);
    }
    loadNetwork(monitor);

    monitor.setProgress(1.0);
}

From source file:org.cytoscape.tableimport.internal.LoadNetworkReaderTask.java

License:Open Source License

@Override
public void run(TaskMonitor monitor) throws Exception {

    monitor.setTitle("Loading network from table");
    monitor.setProgress(0.0);/*ww  w  .j  a  v  a 2 s.co m*/
    monitor.setStatusMessage("Loading network...");
    taskMonitor = monitor;
    int startLoadRowTemp;

    List<String> attrNameList = new ArrayList<String>();
    int colCount;
    String[] attributeNames;

    if (is != null)
        netReader = networkReaderManager.getReader(is, inputName);

    if (netReader == null)
        netReader = networkReaderManager.getReader(uri, inputName);

    if (netReader instanceof CombineReaderAndMappingTask) {
        Workbook workbook = null;
        // Load Spreadsheet data for preview.
        if (fileType != null
                && (fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
                        || fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension()))
                && workbook == null) {
            try {
                workbook = WorkbookFactory.create(new FileInputStream(tempFile));
            } catch (InvalidFormatException e) {
                //e.printStackTrace();
                throw new IllegalArgumentException("Could not read Excel file.  Maybe the file is broken?", e);
            } finally {

            }
        }

        netReader = null;
        if (startLoadRow > 0)
            startLoadRow--;
        startLoadRowTemp = startLoadRow;
        if (firstRowAsColumnNames)
            startLoadRowTemp = 0;

        previewPanel.setPreviewTable(workbook, fileType, tempFile.getAbsolutePath(),
                new FileInputStream(tempFile), delimiters.getSelectedValues(), null, 50, null,
                startLoadRowTemp);

        colCount = previewPanel.getPreviewTable().getColumnModel().getColumnCount();
        importFlag = new boolean[colCount];
        Object curName = null;

        if (firstRowAsColumnNames) {
            setFirstRowAsColumnNames();
            startLoadRow++;
        }

        for (int i = 0; i < colCount; i++) {
            importFlag[i] = true;
            curName = previewPanel.getPreviewTable().getColumnModel().getColumn(i).getHeaderValue();

            if (attrNameList.contains(curName)) {
                int dupIndex = 0;

                for (int idx = 0; idx < attrNameList.size(); idx++) {
                    if (curName.equals(attrNameList.get(idx))) {
                        dupIndex = idx;

                        break;
                    }
                }

                if (importFlag[i] && importFlag[dupIndex]) {
                    //TODO add message to user
                    return;
                }
            }

            if (curName == null) {
                attrNameList.add("Column " + i);
            } else {
                attrNameList.add(curName.toString());
            }
        }

        attributeNames = attrNameList.toArray(new String[0]);

        final Byte[] test = previewPanel.getDataTypes(previewPanel.getSelectedSheetName());

        final Byte[] attributeTypes = new Byte[test.length];

        for (int i = 0; i < test.length; i++) {
            attributeTypes[i] = test[i];
        }

        if (indexColumnSourceInteraction > 0)
            indexColumnSourceInteraction--;

        if (indexColumnTargetInteraction > 0)
            indexColumnTargetInteraction--;

        if (indexColumnTypeInteraction > 0)
            indexColumnTypeInteraction--;

        ntmp = new NetworkTableMappingParameters(delimiters.getSelectedValues(),
                delimitersForDataList.getSelectedValue(), attributeNames, attributeTypes,
                previewPanel.getCurrentListDataTypes(), importFlag, indexColumnSourceInteraction,
                indexColumnTargetInteraction, indexColumnTypeInteraction, defaultInteraction, startLoadRow,
                null);

        if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
                || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) {
            Sheet sheet = workbook.getSheetAt(0);
            networkName = workbook.getSheetName(0);

            reader = new ExcelNetworkSheetReader(networkName, sheet, ntmp, this.nMap, this.rootNetwork);
        } else {
            networkName = this.inputName;
            reader = new NetworkTableReader(networkName, new FileInputStream(tempFile), ntmp, this.nMap,
                    this.rootNetwork);
        }
        loadNetwork(monitor);

        monitor.setProgress(1.0);
    } else {
        networkName = this.inputName;
        insertTasksAfterCurrentTask(netReader);
    }
}

From source file:org.cytoscape.tableimport.internal.task.ImportAttributeTableReaderTask.java

License:Open Source License

@Override
public void run(TaskMonitor tm) throws Exception {
    tm.setTitle("Loading table data");
    tm.setProgress(0.0);/*from   w  ww . ja v a2 s .  co  m*/
    tm.setStatusMessage("Loading table...");

    Workbook workbook = null;

    // Load Spreadsheet data for preview.
    if (fileType != null && (fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
            || fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) && workbook == null) {
        try {
            workbook = WorkbookFactory.create(is);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Could not read Excel file.  Maybe the file is broken?");
        } finally {
            if (is != null)
                is.close();
        }
    }

    if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
            || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) {

        // Fixed bug# 1668, Only load data from the first sheet, ignore the rest sheets
        // UPDATE: From the user perspective it makes more sense to get the selected tab/sheet instead.
        String networkName = amp.getName();

        if (networkName == null)
            networkName = workbook.getSheetName(0);

        final Sheet sheet = workbook.getSheet(networkName);

        if (sheet != null) {
            reader = new ExcelAttributeSheetReader(sheet, amp, serviceRegistrar);
            loadAnnotation(tm);
        }
    } else {
        try {
            reader = new DefaultAttributeTableReader(null, amp, this.is, serviceRegistrar);
            loadAnnotation(tm);
        } catch (Exception ioe) {
            tm.showMessage(TaskMonitor.Level.ERROR, "Unable to read table: " + ioe.getMessage());
        }
    }
}

From source file:org.cytoscape.tableimport.internal.task.ImportNetworkTableReaderTask.java

License:Open Source License

@Override
public void run(TaskMonitor tm) throws Exception {
    tm.setTitle("Loading network from table");
    tm.setProgress(0.0);/*  w w w. j av a 2 s. c om*/
    tm.setStatusMessage("Loading network...");

    Workbook workbook = null;

    // Load Spreadsheet data for preview.
    if (fileType != null && (fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
            || fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) && workbook == null) {
        try {
            workbook = WorkbookFactory.create(is);
        } catch (InvalidFormatException e) {
            throw new IllegalArgumentException("Could not read Excel file.  Maybe the file is broken?", e);
        } finally {
            if (is != null)
                is.close();
        }
    }

    try {
        if (this.fileType.equalsIgnoreCase(SupportedFileType.EXCEL.getExtension())
                || this.fileType.equalsIgnoreCase(SupportedFileType.OOXML.getExtension())) {
            String networkName = ntmp.getName();

            if (networkName == null)
                networkName = workbook.getSheetName(0);

            final Sheet sheet = workbook.getSheet(networkName);

            reader = new ExcelNetworkSheetReader(networkName, sheet, ntmp, nMap, rootNetwork, serviceRegistrar);
        } else {
            reader = new NetworkTableReader(inputName, is, ntmp, nMap, rootNetwork, serviceRegistrar);
        }
    } catch (Exception ioe) {
        tm.showMessage(TaskMonitor.Level.ERROR, "Unable to read table: " + ioe.getMessage());
        return;
    }

    loadNetwork(tm);
    tm.setProgress(1.0);
}