Example usage for org.apache.poi.xssf.usermodel XSSFSheet getMergedRegion

List of usage examples for org.apache.poi.xssf.usermodel XSSFSheet getMergedRegion

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFSheet getMergedRegion.

Prototype

@Override
public CellRangeAddress getMergedRegion(int index) 

Source Link

Document

Returns the merged region at the specified index.

Usage

From source file:com.centurylink.mdw.drools.Excel2007Parser.java

License:Apache License

@SuppressWarnings("deprecation")
private void processSheet(XSSFSheet sheet, List<? extends DataListener> listeners) {

    int mergedRegionCount = sheet.getNumMergedRegions();
    CellRangeAddress[] mergedRanges = new CellRangeAddress[mergedRegionCount];
    for (int i = 0; i < mergedRegionCount; i++) {
        mergedRanges[i] = sheet.getMergedRegion(i);
    }/*from   ww w.  j a  v a  2s  .com*/

    for (int i = 0; i <= sheet.getLastRowNum(); i++) {
        XSSFRow row = sheet.getRow(i);
        if (row != null) {
            newRow(listeners, i, row.getLastCellNum());
            for (int cellNum = 0; cellNum < row.getLastCellNum(); cellNum++) {
                XSSFCell cell = row.getCell(cellNum);
                if (cell != null) {
                    CellRangeAddress merged = getRangeIfMerged(cell, mergedRanges);

                    if (merged != null) {
                        XSSFRow topRow = sheet.getRow(merged.getFirstRow());
                        XSSFCell topLeft = topRow.getCell(merged.getFirstColumn());
                        String cellValue = topLeft.getCellType() == CellType.NUMERIC.getCode()
                                ? String.valueOf(topLeft.getNumericCellValue())
                                : topLeft.getStringCellValue();
                        newCell(listeners, i, cellNum, cellValue, topLeft.getColumnIndex());
                    } else {
                        String cellValue = null;
                        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)
                            cellValue = String.valueOf(cell.getBooleanCellValue());
                        else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
                            cellValue = String.valueOf(cell.getNumericCellValue());
                        else
                            cellValue = cell.getStringCellValue();
                        newCell(listeners, i, cellNum, cellValue, DataListener.NON_MERGED);
                    }
                }
            }
        }
    }
    finishSheet(listeners);
}

From source file:com.centurylink.mdw.workflow.drools.Excel2007Parser.java

License:Apache License

private void processSheet(XSSFSheet sheet, List<? extends DataListener> listeners) {

    int mergedRegionCount = sheet.getNumMergedRegions();
    CellRangeAddress[] mergedRanges = new CellRangeAddress[mergedRegionCount];
    for (int i = 0; i < mergedRegionCount; i++) {
        mergedRanges[i] = sheet.getMergedRegion(i);
    }// w  ww.j a  va  2s  . com

    for (int i = 0; i <= sheet.getLastRowNum(); i++) {
        XSSFRow row = sheet.getRow(i);
        if (row != null) {
            newRow(listeners, i, row.getLastCellNum());
            for (int cellNum = 0; cellNum < row.getLastCellNum(); cellNum++) {
                XSSFCell cell = row.getCell(cellNum);
                if (cell != null) {
                    CellRangeAddress merged = getRangeIfMerged(cell, mergedRanges);

                    if (merged != null) {
                        XSSFRow topRow = sheet.getRow(merged.getFirstRow());
                        XSSFCell topLeft = topRow.getCell(merged.getFirstColumn());
                        newCell(listeners, i, cellNum, topLeft.getStringCellValue(), topLeft.getColumnIndex());
                    } else {
                        String cellValue = null;
                        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)
                            cellValue = String.valueOf(cell.getBooleanCellValue());
                        else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
                            cellValue = String.valueOf(cell.getNumericCellValue());
                        else
                            cellValue = cell.getStringCellValue();
                        newCell(listeners, i, cellNum, cellValue, DataListener.NON_MERGED);
                    }
                }
            }
        }
    }
    finishSheet(listeners);
}

From source file:de.bund.bfr.knime.openkrise.db.imports.custom.bfrnewformat.TraceGenerator.java

License:Open Source License

private XSSFRow copyRow(XSSFWorkbook workbook, XSSFSheet worksheet, int sourceRowNum, int destinationRowNum) {
    XSSFRow sourceRow = worksheet.getRow(sourceRowNum);
    worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1, true, false);
    XSSFRow newRow = worksheet.createRow(destinationRowNum);

    // Loop through source columns to add to new row
    for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
        // Grab a copy of the old/new cell
        XSSFCell oldCell = sourceRow.getCell(i);
        XSSFCell newCell = newRow.createCell(i);

        // If the old cell is null jump to next cell
        if (oldCell == null) {
            newCell = null;//from   w  ww.  j  a  v  a2  s.c  o  m
            continue;
        }

        // Copy style from old cell and apply to new cell
        XSSFCellStyle newCellStyle = workbook.createCellStyle();
        newCellStyle.cloneStyleFrom(oldCell.getCellStyle());

        newCell.setCellStyle(newCellStyle);

        // Set the cell data type
        newCell.setCellType(oldCell.getCellType());

    }

    // If there are are any merged regions in the source row, copy to new row
    for (int i = 0; i < worksheet.getNumMergedRegions(); i++) {
        CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);
        if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {
            CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(),
                    (newRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())),
                    cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
            worksheet.addMergedRegion(newCellRangeAddress);
        }
    }

    newRow.setHeight(sourceRow.getHeight());

    return newRow;
}

From source file:org.apache.ofbiz.pricat.AbstractPricatParser.java

License:Apache License

public void writeCommentsToFile(XSSFWorkbook workbook, XSSFSheet sheet) {
    report.println();/*w  w  w  .  j  ava2s  .  com*/
    report.print(UtilProperties.getMessage(resource, "WriteCommentsBackToExcel", locale),
            InterfaceReport.FORMAT_NOTE);
    FileOutputStream fos = null;
    XSSFCreationHelper factory = workbook.getCreationHelper();
    XSSFFont boldFont = workbook.createFont();
    boldFont.setFontName("Arial");
    boldFont.setBold(true);
    boldFont.setCharSet(134);
    boldFont.setFontHeightInPoints((short) 9);
    XSSFFont plainFont = workbook.createFont();
    plainFont.setFontName("Arial");
    plainFont.setCharSet(134);
    plainFont.setFontHeightInPoints((short) 9);

    XSSFSheet errorSheet = null;
    if (errorMessages.keySet().size() > 0) {
        String errorSheetName = UtilDateTime.nowDateString("yyyy-MM-dd HHmm") + " Errors";
        errorSheetName = WorkbookUtil.createSafeSheetName(errorSheetName);
        errorSheet = workbook.createSheet(errorSheetName);
        workbook.setSheetOrder(errorSheetName, 0);
        workbook.setActiveSheet(workbook.getSheetIndex(errorSheetName));
        XSSFDrawing drawingPatriarch = errorSheet.getDrawingPatriarch();
        if (drawingPatriarch == null) {
            drawingPatriarch = errorSheet.createDrawingPatriarch();
        }
        for (int i = 0; i <= getHeaderRowNo(); i++) {
            XSSFRow newRow = errorSheet.createRow(i);
            XSSFRow row = sheet.getRow(i);
            newRow.setHeight(row.getHeight());
            copyRow(row, newRow, factory, drawingPatriarch);
        }

        // copy merged regions
        for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
            CellRangeAddress mergedRegion = sheet.getMergedRegion(i);
            if (mergedRegion.getFirstRow() < getHeaderRowNo()) {
                errorSheet.addMergedRegion(mergedRegion);
            }
        }

        // copy images
        List<XSSFPictureData> pics = workbook.getAllPictures();
        List<XSSFShape> shapes = sheet.getDrawingPatriarch().getShapes();
        for (int i = 0; i < shapes.size(); i++) {
            XSSFShape shape = shapes.get(i);
            XSSFAnchor anchor = shape.getAnchor();
            if (shape instanceof XSSFPicture && anchor instanceof XSSFClientAnchor) {
                XSSFPicture pic = (XSSFPicture) shape;
                XSSFClientAnchor clientAnchor = (XSSFClientAnchor) anchor;
                if (clientAnchor.getRow1() < getHeaderRowNo()) {
                    for (int j = 0; j < pics.size(); j++) {
                        XSSFPictureData picture = pics.get(j);
                        if (picture.getPackagePart().getPartName()
                                .equals(pic.getPictureData().getPackagePart().getPartName())) {
                            drawingPatriarch.createPicture(clientAnchor, j);
                        }
                    }
                }
            }
        }
    }

    try {
        // set comments in the original sheet
        XSSFDrawing patriarch = sheet.getDrawingPatriarch();
        for (CellReference cell : errorMessages.keySet()) {
            if (cell != null && errorMessages.get(cell) != null) {
                XSSFComment comment = sheet.getCellComment(new CellAddress(cell.getRow(), cell.getCol()));
                boolean isNewComment = false;
                if (comment == null) {
                    XSSFClientAnchor anchor = factory.createClientAnchor();
                    anchor.setDx1(100);
                    anchor.setDx2(100);
                    anchor.setDy1(100);
                    anchor.setDy2(100);
                    anchor.setCol1(cell.getCol());
                    anchor.setCol2(cell.getCol() + 4);
                    anchor.setRow1(cell.getRow());
                    anchor.setRow2(cell.getRow() + 4);
                    anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);

                    comment = patriarch.createCellComment(anchor);
                    isNewComment = true;
                }
                XSSFRichTextString rts = factory.createRichTextString("OFBiz PriCat:\n");
                rts.applyFont(boldFont);
                rts.append(errorMessages.get(cell), plainFont);
                comment.setString(rts);
                comment.setAuthor("Apache OFBiz PriCat");
                if (isNewComment) {
                    sheet.getRow(cell.getRow()).getCell(cell.getCol()).setCellComment(comment);
                    OFBizPricatUtil.formatCommentShape(sheet, cell);
                }
            }
        }

        // set comments in the new error sheet
        XSSFDrawing errorPatriarch = errorSheet.getDrawingPatriarch();
        int newRowNum = getHeaderRowNo() + 1;
        Map<Integer, Integer> rowMapping = new HashMap<Integer, Integer>();
        for (CellReference cell : errorMessages.keySet()) {
            if (cell != null && errorMessages.get(cell) != null) {
                XSSFRow row = sheet.getRow(cell.getRow());
                Integer rowNum = Integer.valueOf(row.getRowNum());
                int errorRow = newRowNum;
                if (rowMapping.containsKey(rowNum)) {
                    errorRow = rowMapping.get(rowNum).intValue();
                } else {
                    XSSFRow newRow = errorSheet.getRow(errorRow);
                    if (newRow == null) {
                        newRow = errorSheet.createRow(errorRow);
                    }
                    rowMapping.put(rowNum, Integer.valueOf(errorRow));
                    newRow.setHeight(row.getHeight());
                    copyRow(row, newRow, factory, errorPatriarch);
                    newRowNum++;
                }
            }
        }

        // write to file
        if (sequenceNum > 0L) {
            File commentedExcel = FileUtil.getFile(tempFilesFolder + userLoginId + "/" + sequenceNum + ".xlsx");
            fos = new FileOutputStream(commentedExcel);
            workbook.write(fos);
        } else {
            fos = new FileOutputStream(pricatFile);
            workbook.write(fos);
        }
        fos.flush();
        fos.close();
        workbook.close();
    } catch (FileNotFoundException e) {
        report.println(e);
        Debug.logError(e, module);
    } catch (IOException e) {
        report.println(e);
        Debug.logError(e, module);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                Debug.logError(e, module);
            }
        }
        if (workbook != null) {
            try {
                workbook.close();
            } catch (IOException e) {
                Debug.logError(e, module);
            }
        }
    }
    report.println(UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK);
    report.println();
}

From source file:org.kuali.test.runner.output.PoiHelper.java

License:Educational Community License

private void copySheets(XSSFSheet newSheet, XSSFSheet sheet) {
    int maxColumnNum = 0;
    Map<Integer, XSSFCellStyle> styleMap = new HashMap<Integer, XSSFCellStyle>();

    int mergedReqionsCount = sheet.getNumMergedRegions();

    for (int i = 0; i < mergedReqionsCount; ++i) {
        newSheet.addMergedRegion(sheet.getMergedRegion(i));
    }/*from   w w w . j a  v a2  s . c o m*/

    for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
        XSSFRow srcRow = sheet.getRow(i);
        XSSFRow destRow = newSheet.createRow(i);
        if (srcRow != null) {
            copyRow(srcRow, destRow, styleMap);
            if (srcRow.getLastCellNum() > maxColumnNum) {
                maxColumnNum = srcRow.getLastCellNum();
            }
        }
    }
    for (int i = 0; i <= maxColumnNum; i++) {
        newSheet.setColumnWidth(i, sheet.getColumnWidth(i));
    }
}

From source file:sv.com.mined.sieni.controller.GestionNotasController.java

public StreamedContent getFilePlantilla() {
    filePlantilla = null;/*from  w  ww. j  ava2s  .co m*/
    String ruthPath = null;
    try {
        if (this.getEvaluacionSubir() != null && this.getEvaluacionSubir().getIdEvaluacion() != null) {
            // Se crea el libro
            XSSFWorkbook libro = new XSSFWorkbook();
            // Se crea una hoja dentro del libro
            XSSFSheet sheetD = libro.createSheet();
            //Obtener lista de alumnos del curso
            List<SieniAlumno> alumnosEval = sieniAlumnoFacadeRemote
                    .findAlumnosInscritos(this.getEvaluacionSubir().getIdCurso().getIdCurso());
            //Leer datos y colocarlos en la hoja
            int f = 0;
            //Guardar datos en celda
            for (SieniAlumno alumno : alumnosEval) {
                // Se crea una fila dentro de la hoja
                XSSFRow fila = sheetD.createRow(f);
                f++;
                // Se crea las celdas dentro de la fila
                XSSFCell celdaCarnet = fila.createCell((short) 0);
                XSSFCell celdaAlumno = fila.createCell((short) 1);
                XSSFCell celdaNota = fila.createCell((short) 2);
                //Colocar valor en celda
                celdaCarnet.setCellValue(alumno.getAlCarnet());
                celdaAlumno.setCellValue(alumno.getNombreCompleto());
                celdaNota.setCellValue((double) 0.00);
            }
            //Encabezados desde plantilla
            InputStream stream = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                    .getContext()).getResourceAsStream("/resources/templates/PlantillaAlumnosEval.xlsx");
            StreamedContent plantillaXLS = new DefaultStreamedContent(stream,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Plantilla.xlsx");
            XSSFWorkbook plantilla = new XSSFWorkbook(plantillaXLS.getStream());
            XSSFSheet sheetP = plantilla.getSheetAt(0);

            //Filas que ocupa el encabezado de plantilla
            int encabezado = 3;
            //Quitar encabezado y desplazar Datos
            sheetD.shiftRows(0, sheetD.getLastRowNum(), encabezado);
            //Copiar contenido de plantilla a la hoja del reporte
            int inicio = 0;
            for (int row = 0; row < encabezado; row++) {
                copyRow(sheetP, sheetD, row, inicio);
                inicio++;
            }
            //Combinar las columnas al igual que la plantilla
            for (int m = 0; m < sheetP.getNumMergedRegions(); m++) {
                CellRangeAddress cellRangeAddress = sheetP.getMergedRegion(m).copy();
                sheetD.addMergedRegion(cellRangeAddress);
            }
            //Evaluacion
            XSSFCell celdaEval = sheetD.getRow(0).getCell(1);
            celdaEval.setCellValue(this.getEvaluacionSubir().getEvNombre());
            // Se salva el libro.
            FileOutputStream elFichero = new FileOutputStream("ListaAlumnos.xlsx");
            libro.write(elFichero);
            elFichero.close();
            //Leer libro para descarga
            FileInputStream file = new FileInputStream(new File("ListaAlumnos.xlsx"));
            filePlantilla = new DefaultStreamedContent(file,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "AlumnosEval.xlsx");

        } else {
            new ValidationPojo().printMsj("Seleccione una evaluacion", FacesMessage.SEVERITY_ERROR);
        }
    } catch (Exception exc) {
        new ValidationPojo().printMsj(
                "Ocurrio un error al descargar plantilla ... consulte con el administrador" + ruthPath,
                FacesMessage.SEVERITY_ERROR);
    }
    return filePlantilla;
}

From source file:tan.jam.jsf.Shifting.java

public static void InsertRow(XSSFWorkbook workbook, XSSFSheet worksheet, int sourceRowNum,
        int destinationRowNum) {

    worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1);
    XSSFRow newRow = worksheet.getRow(destinationRowNum);
    XSSFRow sourceRow = worksheet.getRow(sourceRowNum);

    if (newRow != null) {
        worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1);
    } else {//from   w  ww . ja v  a 2  s . c o  m
        newRow = worksheet.createRow(destinationRowNum);
    }

    for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
        // Grab a copy of the old/new cell
        XSSFCell oldCell = sourceRow.getCell(i);
        XSSFCell newCell = newRow.createCell(i);

        if (oldCell == null) {
            newCell = null;
            continue;
        }

        XSSFCellStyle newCellStyle = workbook.createCellStyle();
        newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
        ;
        newCell.setCellStyle(newCellStyle);

        if (oldCell.getCellComment() != null) {
            newCell.setCellComment(oldCell.getCellComment());
        }

        if (oldCell.getHyperlink() != null) {
            newCell.setHyperlink(oldCell.getHyperlink());
        }

        newCell.setCellType(oldCell.getCellType());

        switch (oldCell.getCellType()) {
        case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BLANK:
            newCell.setCellValue(oldCell.getStringCellValue());
            break;
        case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN:
            newCell.setCellValue(oldCell.getBooleanCellValue());
            break;
        case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_ERROR:
            newCell.setCellErrorValue(oldCell.getErrorCellValue());
            break;
        case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_FORMULA:
            newCell.setCellFormula("+" + "F" + destinationRowNum + "*G" + destinationRowNum);
            break;
        case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC:
            //newCell.setCellValue(oldCell.getNumericCellValue());
            break;
        case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING:
            newCell.setCellValue("");
            break;
        }
    }

    for (int i = 0; i < worksheet.getNumMergedRegions(); i++) {
        CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);
        if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {
            CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(),
                    (newRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())),
                    cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
            worksheet.addMergedRegion(newCellRangeAddress);
        }
    }
    int inc = destinationRowNum + 1;
    worksheet.getRow(destinationRowNum).getCell(7).setCellFormula("+F" + inc + "*G" + inc);
}