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

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

Introduction

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

Prototype

int getColumnIndex();

Source Link

Document

Returns column index of this cell

Usage

From source file:testpoi.Department.java

License:Open Source License

private static void makeEntry(Department deptt) {
    //create new row in xlsx to be generated
    Row newRow = sheetNew.createRow(rowCnt++);
    //Create a new cell in current row
    Cell newCell = newRow.createCell(0);
    //Set value to the department's name
    newCell.setCellValue(deptt.name);//from www.ja v  a2  s .c om
    newCell = newRow.createCell(1);
    newCell.setCellValue(deptt.isNew ? "New" : "Old");
    newCell = newRow.createCell(2);
    newCell.setCellValue(crNo++);

    Row row = null;
    if (deptt.name.equals("Obs & Gynae") && femaleRowNum < sheetFemale.getPhysicalNumberOfRows()) {
        //            //Pick a row from female sheet randomly (Female sheet should have all reproducible ages)
        //            int rowNum = (int)(random*sheetFemale.getPhysicalNumberOfRows());

        row = sheetFemale.getRow(femaleRowNum++);
        System.out.println("Sheet:Female, row: " + row.getRowNum());
    } else if (deptt.name.equals("Paediatrics") && childRowNum < sheetChildren.getPhysicalNumberOfRows()) {
        row = sheetChildren.getRow(childRowNum++);
        System.out.println("Sheet:Children, row: " + row.getRowNum());
    } else //if (allRowNum<sheetAll.getPhysicalNumberOfRows())
    {
        row = sheetAll.getRow(allRowNum++);
        System.out.println("Sheet:All, row: " + row.getRowNum());
    }
    assert row != null;

    //read and write fetched row
    Iterator<Cell> cellIterator = row.cellIterator();
    int newCellCnt = 3;
    while (cellIterator.hasNext()) {
        //May we write all cells as strings?
        Cell cell = cellIterator.next();
        String cellValue = null;
        try {
            if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
                cellValue = (int) (cell.getNumericCellValue()) + "";
            else
                cellValue = cell.getStringCellValue();

            newCell = newRow.createCell(newCellCnt++);
            newCell.setCellValue(cellValue);
        } catch (Exception e) {
            System.out.println("Could not write from cell (value:" + cellValue +
            //                        ", column:"+cell.getSheet().getWorkbook().+
                    ", sheet:" + cell.getSheet().getSheetName() + ", row:" + cell.getRowIndex() + ", column:"
                    + cell.getColumnIndex() + ")");
            e.printStackTrace();
        }
    }
    System.out.println();

    //        //delete row read
    //        if (row.getSheet()==sheetFemale)
    //            sheetFemale.removeRow(row);
    //        else if (row.getSheet()==sheetChildren)
    //            sheetChildren.removeRow(row);
    //        else
    //            sheetAll.removeRow(row);
}

From source file:testpoi.OldDepttSheet.java

License:Open Source License

private static void makeEntry(Department deptt) {
    //create new row in xlsx to be generated
    Row newRow = sheetNew.createRow(rowCnt++);
    //Create a new cell in current row
    Cell newCell = newRow.createCell(0);
    //Set value to the department's name
    newCell.setCellValue(deptt.name);// w ww .  j  a  v  a 2 s  .  c  o  m
    newCell = newRow.createCell(1);
    newCell.setCellValue(deptt.isNew ? "New" : "Old");

    if (deptt.isNew) {
        newCell = newRow.createCell(2);
        newCell.setCellValue(crNo++);

        Row row = null;
        if (deptt.name.equals("Obs & Gynae")) {
            //            //Pick a row from female sheet randomly (Female sheet should have all reproducible ages)
            //            int rowNum = (int)(random*sheetFemale.getPhysicalNumberOfRows());

            if (femaleRowNum < sheetFemale.getPhysicalNumberOfRows()) {
                row = sheetFemale.getRow(femaleRowNum++);
                System.out.println("Sheet:Female, row: " + row.getRowNum());
            } else {
                System.err.println("Female entries exhausted!");
            }
        } else if (deptt.name.equals("Paediatrics")) {
            if (childRowNum < sheetChildren.getPhysicalNumberOfRows()) {
                row = sheetChildren.getRow(childRowNum++);
                System.out.println("Sheet:Children, row: " + row.getRowNum());
            } else {
                System.err.println("Child entries exhausted!");
            }
        } else {
            if (allRowNum < sheetAll.getPhysicalNumberOfRows()) {
                row = sheetAll.getRow(allRowNum++);
                System.out.println("Sheet:All, row: " + row.getRowNum());
            } else {
                System.err.println("All(General New) entries exhausted!");
            }
        }
        if (row == null) {
            throw new IllegalArgumentException("New input Rows Exhausted");
        }
        assert row != null;

        //read and write fetched row
        Iterator<Cell> cellIterator = row.cellIterator();
        int newCellCnt = 3;
        while (cellIterator.hasNext()) {
            //May we write all cells as strings?
            Cell cell = cellIterator.next();
            String cellValue = null;
            try {
                if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
                    cellValue = (int) (cell.getNumericCellValue()) + "";
                else
                    cellValue = cell.getStringCellValue();

                newCell = newRow.createCell(newCellCnt++);
                newCell.setCellValue(cellValue);
            } catch (Exception e) {
                System.out.println("Could not write from cell (value:" + cellValue +
                //                        ", column:"+cell.getSheet().getWorkbook().+
                        ", sheet:" + cell.getSheet().getSheetName() + ", row:" + cell.getRowIndex()
                        + ", column:" + cell.getColumnIndex() + ")");
                e.printStackTrace();
            }
        }
    } else //deptt is old
    {
        OldDepttSheet oldDepttSheetToUse = depttToOldSheetsMap.get(deptt.name);

        Row row = oldDepttSheetToUse.sheet.getRow(oldDepttSheetToUse.rowCnt++);

        if (row == null) {
            throw new IllegalArgumentException("Old Input Rows Exhausted in department " + deptt.name);
        }

        System.out.println("Sheet:" + deptt.name + ", row: " + row.getRowNum());

        //Copy row from old sheet to newRow
        int newCellCnt = 2;
        Iterator<Cell> cellIterator = row.cellIterator();
        //Skip columns Department and Patient Type
        cellIterator.next();
        cellIterator.next();

        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            String cellValue = null;
            try {
                if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
                    cellValue = (int) (cell.getNumericCellValue()) + "";
                else
                    cellValue = cell.getStringCellValue();

                newCell = newRow.createCell(newCellCnt++);
                newCell.setCellValue(cellValue);
            } catch (Exception e) {
                System.out.println("Could not write from old sheet cell (value:" + cellValue + ", sheet:"
                        + cell.getSheet().getSheetName() + ", row:" + cell.getRowIndex() + ", column:"
                        + cell.getColumnIndex() + ")");
                e.printStackTrace();
            }

        }
    }
}

From source file:th.co.aoe.makedev.missconsult.exam.service.impl.ReadWriteWorkbook_bk.java

License:Apache License

public static List<MissQuestion> setQuestion() {
    //???/*from   w w w . ja  v  a 2s  .  c  o m*/
    FileInputStream fileIn = null;
    //  FileOutputStream fileOut = null;
    List<MissQuestion> missQuestions = new ArrayList<MissQuestion>();
    try {
        try {
            //fileIn = new FileInputStream("/usr/local/data/Work/PROJECT/MakeDev/Exam/Question_Test/Service_Attitude.xls"); // ok
            //fileIn = new FileInputStream("/usr/local/data/Work/PROJECT/MakeDev/Exam/Question_Test/EPT_PLUS_THAI.xls");// ok
            //fileIn = new FileInputStream("/usr/local/data/Work/PROJECT/MakeDev/Exam/Question_Test/The4Factors_1.xls"); // ok
            //   fileIn = new FileInputStream("/usr/local/data/Work/PROJECT/MakeDev/Exam/Question_Test/The4Factors_2.xls"); // ok
            //fileIn = new FileInputStream("/usr/local/data/Work/PROJECT/MakeDev/Exam/Question_Test/LeadershipAssessment_1.xls"); // ok
            fileIn = new FileInputStream(
                    "/usr/local/data/Work/PROJECT/MakeDev/Exam/Question_Test/LeadershipAssessment_2.xls"); // ok
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        POIFSFileSystem fs = null;
        try {
            fs = new POIFSFileSystem(fileIn);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HSSFWorkbook wb = null;
        try {
            wb = new HSSFWorkbook(fs);
            HSSFSheet sheet = wb.getSheetAt(0);
            for (Row row : sheet) {
                //System.out.println("row id="+row.getRowNum()+"");
                MissQuestion missQuestion = new MissQuestion();
                //int rowId=row.getRowNum();
                //if(rowId>0){
                //   ThaiCustomUser user =new ThaiCustomUser();
                for (Cell cell : row) {

                    int columnIndex = cell.getColumnIndex();
                    String value = "";
                    //System.out.println("  row id="+cell.getRowIndex()+",column id="+columnIndex+"");  

                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        if (columnIndex == 0) {
                            value = cell.getStringCellValue();
                            //    System.out.println("      CELL_TYPE_STRING="+value);
                            missQuestion.setMqId(Long.parseLong((cell.getRowIndex() + 1) + ""));
                            missQuestion.setMqNameTh1(value);
                            missQuestions.add(missQuestion);
                        }
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            // System.out.println("      CELL_TYPE_NUMERIC DATE="+cell.getDateCellValue());
                        } else {
                            double valuecel = cell.getNumericCellValue();
                            NumberFormat format = NumberFormat.getNumberInstance();
                            // format.setMaximumIntegerDigits(99);
                            format.setGroupingUsed(false);

                            // System.out.println("      CELL_TYPE_NUMERIC="+format.format(valuecel));
                            value = format.format(valuecel);
                            //System.out.println("      CELL_TYPE_NUMERIC="+Double.toString(cell.getNumericCellValue()));
                            // System.out.println("      CELL_TYPE_NUMERIC="+cell.getNumericCellValue());
                            /* Date    date    = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
                                DateFormat  format2  = new     SimpleDateFormat("yyyyMMdd");
                               System.out.println("      CELL_TYPE_NUMERIC date="+format2.format(date));
                            */
                        }
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        // System.out.println(cell.getBooleanCellValue());
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        // System.out.println("yy="+cell.getCellFormula());
                        break;
                    default:
                        //  System.out.println();
                    }
                }
            }
            // } 
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } finally {

        if (fileIn != null)
            try {
                fileIn.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
    return missQuestions;
}

From source file:tools.parsing.ExcelReader.java

public void readExcel() {
    try {//from   w  w  w  .  j a  va  2  s.  c o  m
        FileInputStream file = new FileInputStream(new File(this.filePath));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            Comment comment = new Comment();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                    if (cell.getColumnIndex() == 0)
                        comment.setTopic(cell.getNumericCellValue() + "");
                    else if (cell.getColumnIndex() == 1)
                        comment.setCode(cell.getNumericCellValue() + "");
                    else if (cell.getColumnIndex() == 2)
                        comment.setAuthor(cell.getNumericCellValue() + "");
                    else if (cell.getColumnIndex() == 3)
                        comment.setDate(cell.getNumericCellValue() + "");
                    else
                        comment.setComment(cell.getNumericCellValue() + "");
                    break;
                case Cell.CELL_TYPE_STRING:
                    if (cell.getColumnIndex() == 0)
                        comment.setTopic(cell.getStringCellValue());
                    else if (cell.getColumnIndex() == 1)
                        comment.setCode(cell.getStringCellValue());
                    else if (cell.getColumnIndex() == 2)
                        comment.setAuthor(cell.getStringCellValue());
                    else if (cell.getColumnIndex() == 3)
                        comment.setDate(cell.getStringCellValue());
                    else
                        comment.setComment(cell.getStringCellValue());
                    break;
                }
            }
            this.comments.add(comment);
        }
        file.close();
    } catch (IOException e) {
        Logger.getLogger(ExcelReader.class.getName()).log(Level.SEVERE, null, e);
    }
}

From source file:uk.co.certait.htmlexporter.writer.excel.ExcelStyleGenerator.java

License:Apache License

protected void applyWidth(Cell cell, Style style) {
    if (style.getProperty(CssIntegerProperty.WIDTH) > 0) {
        cell.getSheet().setColumnWidth(cell.getColumnIndex(), style.getProperty(CssIntegerProperty.WIDTH) * 50);
    }/*w w  w.j a v  a2s.  co m*/
}

From source file:uk.co.spudsoft.birt.emitters.excel.handlers.CellContentHandler.java

License:Open Source License

/**
 * Finish processing for the current (real) cell.
 * @param element//from  www  .j  a v  a2  s.c o m
 * The element that signifies the end of the cell (this may not be an ICellContent object if the 
 * cell is created for a label or text outside of a table). 
 */
protected void endCellContent(HandlerState state, ICellContent birtCell, IContent element, Cell cell,
        Area area) {
    StyleManager sm = state.getSm();
    StyleManagerUtils smu = state.getSmu();

    BirtStyle birtCellStyle = null;
    if (birtCell != null) {
        birtCellStyle = new BirtStyle(birtCell);
        if (element != null) {
            // log.debug( "Overlaying style from ", element );
            birtCellStyle.overlay(element);
        }
    } else if (element != null) {
        birtCellStyle = new BirtStyle(element);
    } else {
        birtCellStyle = new BirtStyle(state.getSm().getCssEngine());
    }
    if (preferredAlignment != null) {
        birtCellStyle.setProperty(StyleConstants.STYLE_TEXT_ALIGN, preferredAlignment);
    }
    if (CSSConstants.CSS_TRANSPARENT_VALUE
            .equals(birtCellStyle.getString(StyleConstants.STYLE_BACKGROUND_COLOR))) {
        if (parent != null) {
            birtCellStyle.setProperty(StyleConstants.STYLE_BACKGROUND_COLOR, parent.getBackgroundColour());
        }
    }
    if (hyperlinkUrl != null) {
        Hyperlink hyperlink = cell.getSheet().getWorkbook().getCreationHelper()
                .createHyperlink(Hyperlink.LINK_URL);
        hyperlink.setAddress(hyperlinkUrl);
        cell.setHyperlink(hyperlink);
    }
    if (hyperlinkBookmark != null) {
        Hyperlink hyperlink = cell.getSheet().getWorkbook().getCreationHelper()
                .createHyperlink(Hyperlink.LINK_DOCUMENT);
        hyperlink.setAddress(prepareName(hyperlinkBookmark));
        cell.setHyperlink(hyperlink);
    }

    if (lastValue != null) {
        if (lastValue instanceof String) {
            String lastString = (String) lastValue;

            smu.correctFontColorIfBackground(birtCellStyle);
            for (RichTextRun run : richTextRuns) {
                run.font = smu.correctFontColorIfBackground(sm.getFontManager(), state.getWb(), birtCellStyle,
                        run.font);
            }

            if (!richTextRuns.isEmpty()) {
                RichTextString rich = smu.createRichTextString(lastString);
                int runStart = richTextRuns.get(0).startIndex;
                Font lastFont = richTextRuns.get(0).font;
                for (int i = 0; i < richTextRuns.size(); ++i) {
                    RichTextRun run = richTextRuns.get(i);
                    log.debug("Run: ", run.startIndex, " font :", run.font);
                    if (!lastFont.equals(run.font)) {
                        log.debug("Applying ", runStart, " - ", run.startIndex);
                        rich.applyFont(runStart, run.startIndex, lastFont);
                        runStart = run.startIndex;
                        lastFont = richTextRuns.get(i).font;
                    }
                }

                log.debug("Finalising with ", runStart, " - ", lastString.length());
                rich.applyFont(runStart, lastString.length(), lastFont);

                setCellContents(cell, rich);
            } else {
                setCellContents(cell, lastString);
            }

            if (lastString.contains("\n")) {
                if (!CSSConstants.CSS_NOWRAP_VALUE.equals(lastElement.getStyle().getWhiteSpace())) {
                    birtCellStyle.setProperty(StyleConstants.STYLE_WHITE_SPACE,
                            new StringValue(StringValue.CSS_STRING, CSSConstants.CSS_PRE_VALUE));
                }
            }
            if (!richTextRuns.isEmpty()) {
                birtCellStyle.setProperty(StyleConstants.STYLE_VERTICAL_ALIGN,
                        new StringValue(StringValue.CSS_STRING, CSSConstants.CSS_TOP_VALUE));
            }
            if (preferredAlignment != null) {
                birtCellStyle.setProperty(StyleConstants.STYLE_TEXT_ALIGN, preferredAlignment);
            }

        } else {
            setCellContents(cell, lastValue);
        }
    }

    int colIndex = cell.getColumnIndex();
    state.getSmu().applyAreaBordersToCell(state.areaBorders, cell, birtCellStyle, state.rowNum, colIndex);

    if ((birtCell != null) && ((birtCell.getColSpan() > 1) || (birtCell.getRowSpan() > 1))) {
        AreaBorders mergedRegionBorders = AreaBorders.createForMergedCells(
                state.rowNum + birtCell.getRowSpan() - 1, colIndex, colIndex + birtCell.getColSpan() - 1,
                state.rowNum, birtCellStyle);
        if (mergedRegionBorders != null) {
            state.insertBorderOverload(mergedRegionBorders);
        }
    }

    String customNumberFormat = EmitterServices.stringOption(state.getRenderOptions(), element,
            ExcelEmitter.CUSTOM_NUMBER_FORMAT, null);
    if (customNumberFormat != null) {
        StyleManagerUtils.setNumberFormat(birtCellStyle, ExcelEmitter.CUSTOM_NUMBER_FORMAT + customNumberFormat,
                null);
    }

    setCellStyle(sm, cell, birtCellStyle, lastValue);

    // Excel auto calculates the row height (if it isn't specified) as long as the cell isn't merged - if it is merged I have to do it
    if (((colSpan > 1) || (state.rowHasSpans(state.rowNum)))
            && ((lastValue instanceof String) || (lastValue instanceof RichTextString))) {
        int spannedRowAlgorithm = EmitterServices.integerOption(state.getRenderOptions(), element,
                ExcelEmitter.SPANNED_ROW_HEIGHT, ExcelEmitter.SPANNED_ROW_HEIGHT_SPREAD);
        Font defaultFont = state.getWb().getFontAt(cell.getCellStyle().getFontIndex());
        double cellWidth = spanWidthMillimetres(state.currentSheet, cell.getColumnIndex(),
                cell.getColumnIndex() + colSpan - 1);
        float cellDesiredHeight = smu.calculateTextHeightPoints(cell.getStringCellValue(), defaultFont,
                cellWidth, richTextRuns);
        if (cellDesiredHeight > state.requiredRowHeightInPoints) {
            int rowSpan = birtCell.getRowSpan();
            if (rowSpan < 2) {
                state.requiredRowHeightInPoints = cellDesiredHeight;
            } else {
                switch (spannedRowAlgorithm) {
                case ExcelEmitter.SPANNED_ROW_HEIGHT_FIRST:
                    state.requiredRowHeightInPoints = cellDesiredHeight;
                    break;
                case ExcelEmitter.SPANNED_ROW_HEIGHT_IGNORED:
                    break;
                default:
                    if (area != null) {
                        area.setHeight(cellDesiredHeight);
                    }
                }
            }
        }
    }

    // Adjust the required row height for any relevant areas based on what's left 
    float rowSpanHeightRequirement = state.calculateRowSpanHeightRequirement(state.rowNum);
    if (rowSpanHeightRequirement > state.requiredRowHeightInPoints) {
        state.requiredRowHeightInPoints = rowSpanHeightRequirement;
    }

    if (EmitterServices.booleanOption(state.getRenderOptions(), element, ExcelEmitter.FREEZE_PANES, false)) {
        if (state.currentSheet.getPaneInformation() == null) {
            state.currentSheet.createFreezePane(state.colNum, state.rowNum);
        }
    }

    lastValue = null;
    lastElement = null;
    richTextRuns.clear();
}

From source file:uk.co.spudsoft.birt.emitters.excel.handlers.CellContentHandler.java

License:Open Source License

/**
 * Set the contents of an empty cell./*  ww w .  ja  v a2s  .  c om*/
 * This should now be the only way in which a cell value is set (cells should not be modified). 
 * @param value
 * The value to set.
 * @param element
 * The BIRT element supplying the value, used to set the style of the cell.
 */
private <T> void setCellContents(Cell cell, Object value) {
    log.debug("Setting cell[", cell.getRow().getRowNum(), ",", cell.getColumnIndex(), "] value to ", value);
    if (value instanceof Double) {
        // cell.setCellType(Cell.CELL_TYPE_NUMERIC);
        cell.setCellValue((Double) value);
        lastValue = value;
    } else if (value instanceof Integer) {
        // cell.setCellType(Cell.CELL_TYPE_NUMERIC);
        cell.setCellValue((Integer) value);
        lastValue = value;
    } else if (value instanceof Long) {
        // cell.setCellType(Cell.CELL_TYPE_NUMERIC);
        cell.setCellValue((Long) value);
        lastValue = value;
    } else if (value instanceof Date) {
        // cell.setCellType(Cell.CELL_TYPE_NUMERIC);
        cell.setCellValue((Date) value);
        lastValue = value;
    } else if (value instanceof Boolean) {
        // cell.setCellType(Cell.CELL_TYPE_BOOLEAN);
        cell.setCellValue(((Boolean) value).booleanValue());
        lastValue = value;
    } else if (value instanceof BigDecimal) {
        // cell.setCellType(Cell.CELL_TYPE_NUMERIC);
        cell.setCellValue(((BigDecimal) value).doubleValue());
        lastValue = value;
    } else if (value instanceof String) {
        // cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue((String) value);
        lastValue = value;
    } else if (value instanceof RichTextString) {
        // cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue((RichTextString) value);
        lastValue = value;
    } else if (value != null) {
        log.debug("Unhandled data: ", (value == null ? "<null>" : value));
        // cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue(value.toString());
        lastValue = value;
    }
}

From source file:uk.co.spudsoft.birt.emitters.excel.handlers.PageHandler.java

License:Open Source License

/**
 * <p>// w w  w .  ja v a  2 s  .c o m
 * Process a CellImage from the images list and place the image on the sheet.
 * </p><p>
 * This involves changing the row height as necesssary and determining the column spread of the image.
 * </p>
 * @param cellImage
 * The image to be placed on the sheet.
 */
private void processCellImage(HandlerState state, Drawing drawing, CellImage cellImage) {
    Coordinate location = cellImage.location;

    Cell cell = state.currentSheet.getRow(location.getRow()).getCell(location.getCol());

    IImageContent image = cellImage.image;

    StyleManagerUtils smu = state.getSmu();
    float ptHeight = cell.getRow().getHeightInPoints();
    if (image.getHeight() != null) {
        ptHeight = smu.fontSizeInPoints(image.getHeight().toString());
    }

    // Get image width
    int endCol = cell.getColumnIndex();
    double lastColWidth = ClientAnchorConversions
            .widthUnits2Millimetres((short) state.currentSheet.getColumnWidth(endCol)) + 2.0;
    int dx = smu.anchorDxFromMM(lastColWidth, lastColWidth);
    double mmWidth = 0.0;
    if (smu.isAbsolute(image.getWidth())) {
        mmWidth = image.getWidth().convertTo(DimensionType.UNITS_MM);
    } else if (smu.isPixels(image.getWidth())) {
        mmWidth = ClientAnchorConversions.pixels2Millimetres(image.getWidth().getMeasure());
    }
    // Allow image to span multiple columns
    CellRangeAddress mergedRegion = getMergedRegionBegunBy(state.currentSheet, location.getRow(),
            location.getCol());
    if ((cellImage.spanColumns) || (mergedRegion != null)) {
        log.debug("Image size: ", image.getWidth(), " translates as mmWidth = ", mmWidth);
        if (mmWidth > 0) {
            double mmAccumulatedWidth = 0;
            int endColLimit = cellImage.spanColumns ? 256 : mergedRegion.getLastColumn();
            for (endCol = cell.getColumnIndex(); mmAccumulatedWidth < mmWidth
                    && endCol < endColLimit; ++endCol) {
                lastColWidth = ClientAnchorConversions
                        .widthUnits2Millimetres((short) state.currentSheet.getColumnWidth(endCol)) + 2.0;
                mmAccumulatedWidth += lastColWidth;
                log.debug("lastColWidth = ", lastColWidth, "; mmAccumulatedWidth = ", mmAccumulatedWidth);
            }
            if (mmAccumulatedWidth > mmWidth) {
                mmAccumulatedWidth -= lastColWidth;
                --endCol;
                double mmShort = mmWidth - mmAccumulatedWidth;
                dx = smu.anchorDxFromMM(mmShort, lastColWidth);
            }
        }
    } else {
        float widthRatio = (float) (mmWidth / lastColWidth);
        ptHeight = ptHeight / widthRatio;
    }

    int rowsSpanned = state.findRowsSpanned(cell.getRowIndex(), cell.getColumnIndex());
    float neededRowHeightPoints = ptHeight;

    for (int i = 0; i < rowsSpanned; ++i) {
        int rowIndex = cell.getRowIndex() + 1 + i;
        neededRowHeightPoints -= state.currentSheet.getRow(rowIndex).getHeightInPoints();
    }

    if (neededRowHeightPoints > cell.getRow().getHeightInPoints()) {
        cell.getRow().setHeightInPoints(neededRowHeightPoints);
    }

    // ClientAnchor anchor = wb.getCreationHelper().createClientAnchor();
    ClientAnchor anchor = state.getWb().getCreationHelper().createClientAnchor();
    anchor.setCol1(cell.getColumnIndex());
    anchor.setRow1(cell.getRowIndex());
    anchor.setCol2(endCol);
    anchor.setRow2(cell.getRowIndex() + rowsSpanned);
    anchor.setDx2(dx);
    anchor.setDy2(smu.anchorDyFromPoints(ptHeight, cell.getRow().getHeightInPoints()));
    anchor.setAnchorType(ClientAnchor.MOVE_DONT_RESIZE);
    drawing.createPicture(anchor, cellImage.imageIdx);
}

From source file:uk.co.spudsoft.birt.emitters.excel.StyleManagerUtils.java

License:Open Source License

public void extendRows(HandlerState state, int startRow, int startCol, int endRow, int endCol) {
    for (int colNum = startCol; colNum < endCol; ++colNum) {
        Cell lastCell = null;
        for (int rowNum = startRow; rowNum < endRow; ++rowNum) {
            Row row = state.currentSheet.getRow(rowNum);
            if (row != null) {
                Cell cell = row.getCell(colNum);
                if (cell != null) {
                    lastCell = cell;//from   w  w  w  .j  a  v  a 2s . c o  m
                }
            }
        }
        if ((lastCell != null) && (lastCell.getRowIndex() < endRow - 1)) {
            CellRangeAddress range = new CellRangeAddress(lastCell.getRowIndex(), endRow - 1,
                    lastCell.getColumnIndex(), lastCell.getColumnIndex());
            log.debug("Extend: merging from [", range.getFirstRow(), ",", range.getFirstColumn(), "] to [",
                    range.getLastRow(), ",", range.getLastColumn(), "]");
            state.currentSheet.addMergedRegion(range);
            for (int rowNum = lastCell.getRowIndex() + 1; rowNum < endRow; ++rowNum) {
                Row row = state.currentSheet.getRow(rowNum);
                if (row == null) {
                    log.error(0,
                            "Creating a row (for column " + colNum + "), this really shouldn't be necessary",
                            null);
                    row = state.currentSheet.createRow(rowNum);
                }
                Cell cell = row.createCell(colNum);
                cell.setCellStyle(lastCell.getCellStyle());
            }
        }
    }
}

From source file:uk.co.spudsoft.birt.emitters.excel.tests.CellRangeTester.java

License:Open Source License

protected void validateCellRange(Matcher matcher, Cell cell) {
    int desiredR1 = Integer.parseInt(matcher.group(1));
    int desiredC1 = Integer.parseInt(matcher.group(2));
    int desiredR2 = Integer.parseInt(matcher.group(3));
    int desiredC2 = Integer.parseInt(matcher.group(4));

    int actualR1 = cell.getRowIndex() + 1;
    int actualC1 = cell.getColumnIndex() + 1;
    int actualR2 = actualR1;
    int actualC2 = actualC1;

    for (int i = 0; i < cell.getSheet().getNumMergedRegions(); ++i) {
        CellRangeAddress cra = cell.getSheet().getMergedRegion(i);
        if ((cra.getFirstRow() == cell.getRowIndex()) && (cra.getFirstColumn() == cell.getColumnIndex())) {
            assertEquals(actualR1, actualR2);
            assertEquals(actualC1, actualC2);
            actualR2 = cra.getLastRow() + 1;
            actualC2 = cra.getLastColumn() + 1;
        }//from w  ww.j  a  v a2 s. c om
    }
    assertEquals(desiredR1, actualR1);
    assertEquals(desiredC1, actualC1);
    assertEquals(desiredR2, actualR2);
    assertEquals(desiredC2, actualC2);
}