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

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

Introduction

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

Prototype

void setCellComment(Comment comment);

Source Link

Document

Assign a comment to this cell

Usage

From source file:it.eng.spagobi.engines.worksheet.services.export.ExportWorksheetAction.java

License:Mozilla Public License

public void exportMetadataToXLS(Workbook wb, WorkSheetXLSExporter exporter, CreationHelper createHelper,
        JSONArray metadataPropertiesJSON, JSONArray parametersJSON) throws Exception {

    int FIRST_ROW = 0;
    int FIRST_COLUMN = 0;
    int rowCount = 0;

    JSONArray technicalMetadataProperty;
    JSONArray shortBusinessMetadataProperty;
    JSONArray longBusinessMetadataProperty;

    org.apache.poi.ss.usermodel.Sheet sheet = wb
            .createSheet(EngineMessageBundle.getMessage("worksheet.export.metadata.title", this.getLocale()));

    sheet.setColumnWidth(FIRST_COLUMN, 256 * 25);
    sheet.setColumnWidth(FIRST_COLUMN + 1, 256 * 90);

    CellStyle headerCellStyle = exporter.buildMetadataTitleCellStyle(sheet);
    CellStyle metaNameCellStyle = exporter.buildMetadataNameCellStyle(sheet);
    CellStyle metaValueCellStyle = exporter.buildMetadataValueCellStyle(sheet);

    Row row;//from   w ww  .  j  a  va2  s  .com
    Cell nameCell;
    Cell valueCell;
    Cell headerCell;
    String text;

    technicalMetadataProperty = new JSONArray();
    shortBusinessMetadataProperty = new JSONArray();
    longBusinessMetadataProperty = new JSONArray();

    if (metadataPropertiesJSON != null) {
        for (int i = 0; i < metadataPropertiesJSON.length(); i++) {
            JSONObject metadataProperty = metadataPropertiesJSON.getJSONObject(i);
            String metadataPropertyType = metadataProperty.getString("meta_type");
            if ("SHORT_TEXT".equalsIgnoreCase(metadataPropertyType)) {
                shortBusinessMetadataProperty.put(metadataProperty);
                continue;
            } else if ("LONG_TEXT".equalsIgnoreCase(metadataPropertyType)) {
                longBusinessMetadataProperty.put(metadataProperty);
                continue;
            } else {
                technicalMetadataProperty.put(metadataProperty);
            }

        }

    }

    if (technicalMetadataProperty.length() > 0) {

        row = sheet.createRow((FIRST_ROW) + rowCount);
        headerCell = row.createCell(FIRST_COLUMN + 1);
        headerCell = row.createCell(FIRST_COLUMN + 1);
        text = EngineMessageBundle.getMessage("worksheet.export.metadata.technicalMetadata", this.getLocale());
        headerCell.setCellValue(createHelper.createRichTextString(text));
        headerCell.setCellType(exporter.getCellTypeString());
        headerCell.setCellStyle(headerCellStyle);

        rowCount++;

        for (int i = 0; i < technicalMetadataProperty.length(); i++) {
            JSONObject metadataProperty = technicalMetadataProperty.getJSONObject(i);

            String metadataPropertyName = metadataProperty.getString("meta_name");
            String metadataPropertyValue = metadataProperty.getString("meta_content");
            row = sheet.createRow((FIRST_ROW) + rowCount);

            nameCell = row.createCell(FIRST_COLUMN);
            nameCell.setCellValue(createHelper.createRichTextString(metadataPropertyName));
            nameCell.setCellType(exporter.getCellTypeString());
            nameCell.setCellStyle(metaNameCellStyle);

            valueCell = row.createCell(FIRST_COLUMN + 1);
            valueCell.setCellValue(createHelper.createRichTextString(metadataPropertyValue));
            valueCell.setCellType(exporter.getCellTypeString());
            valueCell.setCellStyle(metaValueCellStyle);
            rowCount++;
        }

        rowCount = rowCount + 2;

    }

    if (shortBusinessMetadataProperty.length() + longBusinessMetadataProperty.length() > 0) {

        row = sheet.createRow((FIRST_ROW) + rowCount);
        headerCell = row.createCell(FIRST_COLUMN + 1);
        headerCell = row.createCell(FIRST_COLUMN + 1);
        text = EngineMessageBundle.getMessage("worksheet.export.metadata.businessMetadata", this.getLocale());
        headerCell.setCellValue(createHelper.createRichTextString(text));
        headerCell.setCellType(exporter.getCellTypeString());
        headerCell.setCellStyle(headerCellStyle);
        rowCount++;

        for (int i = 0; i < shortBusinessMetadataProperty.length(); i++, rowCount++) {

            JSONObject metadataProperty = shortBusinessMetadataProperty.getJSONObject(i);

            String metadataPropertyName = metadataProperty.getString("meta_name");
            String metadataPropertyValue = metadataProperty.getString("meta_content");
            row = sheet.createRow((FIRST_ROW) + rowCount);

            nameCell = row.createCell(FIRST_COLUMN);
            nameCell.setCellValue(createHelper.createRichTextString(metadataPropertyName));
            nameCell.setCellType(exporter.getCellTypeString());
            nameCell.setCellStyle(metaNameCellStyle);

            valueCell = row.createCell(FIRST_COLUMN + 1);
            valueCell.setCellValue(createHelper.createRichTextString(metadataPropertyValue));
            valueCell.setCellType(exporter.getCellTypeString());
            valueCell.setCellStyle(metaValueCellStyle);
        }

        for (int i = 0; i < longBusinessMetadataProperty.length(); i++, rowCount++) {

            JSONObject metadataProperty = longBusinessMetadataProperty.getJSONObject(i);

            String metadataPropertyName = metadataProperty.getString("meta_name");
            String metadataPropertyValue = metadataProperty.getString("meta_content");

            row = sheet.createRow((FIRST_ROW) + rowCount);

            nameCell = row.createCell(FIRST_COLUMN);
            nameCell.setCellValue(createHelper.createRichTextString(metadataPropertyName));
            nameCell.setCellType(exporter.getCellTypeString());
            nameCell.setCellStyle(metaNameCellStyle);

            valueCell = row.createCell(FIRST_COLUMN + 1);
            valueCell.setCellValue(createHelper.createRichTextString(metadataPropertyValue));
            valueCell.setCellType(exporter.getCellTypeString());
            valueCell.setCellStyle(metaValueCellStyle);
        }

        rowCount = rowCount + 2;

    }

    if (parametersJSON.length() > 0) {

        row = sheet.createRow((FIRST_ROW) + rowCount);
        headerCell = row.createCell(FIRST_COLUMN + 1);
        headerCell = row.createCell(FIRST_COLUMN + 1);
        text = EngineMessageBundle.getMessage("worksheet.export.metadata.analyticalDrivers", this.getLocale());
        headerCell.setCellValue(createHelper.createRichTextString(text));
        headerCell.setCellType(exporter.getCellTypeString());
        headerCell.setCellStyle(headerCellStyle);

        rowCount++;

        Drawing drawing = sheet.createDrawingPatriarch();

        for (int i = 0; i < parametersJSON.length(); i++) {
            JSONObject parameterJSON = parametersJSON.getJSONObject(i);
            String name = parameterJSON.getString("name");
            String value = parameterJSON.getString("value");
            String description = parameterJSON.optString("description");

            row = sheet.createRow((FIRST_ROW) + rowCount);

            nameCell = row.createCell(FIRST_COLUMN);
            nameCell.setCellValue(createHelper.createRichTextString(name));
            nameCell.setCellType(exporter.getCellTypeString());
            nameCell.setCellStyle(metaNameCellStyle);

            valueCell = row.createCell(FIRST_COLUMN + 1);

            if (StringUtilities.isNotEmpty(description)) {

                valueCell.setCellValue(createHelper.createRichTextString(description));

                ClientAnchor anchor = createHelper.createClientAnchor();
                anchor.setCol1(valueCell.getColumnIndex());
                anchor.setCol2(valueCell.getColumnIndex() + 1);
                anchor.setRow1(row.getRowNum());
                anchor.setRow2(row.getRowNum() + 3);

                Comment comment = drawing.createCellComment(anchor);
                RichTextString str = createHelper.createRichTextString(value);
                comment.setString(str);
                comment.setAuthor("SpagoBI");

                valueCell.setCellComment(comment);
            } else {
                valueCell.setCellValue(createHelper.createRichTextString(value));
            }
            valueCell.setCellType(exporter.getCellTypeString());
            valueCell.setCellStyle(metaValueCellStyle);
            rowCount++;
        }

    }

}

From source file:jp.ryoyamamoto.poiutils.Cells.java

License:Apache License

private static void copyCellComment(Cell source, Cell target) {
    target.setCellComment(source.getCellComment());
}

From source file:net.ceos.project.poi.annotated.core.CellStyleHandler.java

License:Apache License

/**
 * Apply the cell comment to a cell.//from ww  w. j a v a  2  s. co  m
 * 
 * @param configCriteria
 *            the {@link XConfigCriteria} object
 * @param isAuthorizedComment
 *            the extension file
 * @param cell
 *            the {@link Cell}
 */
protected static void applyComment(final XConfigCriteria configCriteria, final Boolean isAuthorizedComment,
        final Cell cell) {
    if (StringUtils.isBlank(configCriteria.getElement().commentRules())
            || StringUtils.isNotBlank(configCriteria.getElement().commentRules()) && isAuthorizedComment) {
        if (ExtensionFileType.XLS.equals(configCriteria.getExtension())) {
            final Map<Sheet, HSSFPatriarch> drawingPatriarches = new HashMap<>();

            CreationHelper createHelper = cell.getSheet().getWorkbook().getCreationHelper();
            HSSFSheet sheet = (HSSFSheet) cell.getSheet();
            HSSFPatriarch drawingPatriarch = drawingPatriarches.get(sheet);
            if (drawingPatriarch == null) {
                drawingPatriarch = sheet.createDrawingPatriarch();
                drawingPatriarches.put(sheet, drawingPatriarch);
            }

            Comment comment = drawingPatriarch
                    .createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
            comment.setString(createHelper.createRichTextString(configCriteria.getElement().comment()));

            cell.setCellComment(comment);

        } else if (ExtensionFileType.XLSX.equals(configCriteria.getExtension())) {
            CreationHelper factory = configCriteria.getWorkbook().getCreationHelper();

            Drawing drawing = cell.getSheet().createDrawingPatriarch();

            ClientAnchor anchor = factory.createClientAnchor();

            Comment comment = drawing.createCellComment(anchor);
            RichTextString str = factory.createRichTextString(configCriteria.getElement().comment());
            comment.setString(str);

            cell.setCellComment(comment);
        }
    }
}

From source file:nl.b3p.viewer.features.ExcelDownloader.java

License:Open Source License

@Override
public void init() throws IOException {
    wb = new XSSFWorkbook();

    styles = createStyles(wb);/*  ww w . j  ava2 s .  c  om*/

    sheet = wb.createSheet(fs.getName().toString());

    //turn off gridlines
    sheet.setDisplayGridlines(false);
    sheet.setPrintGridlines(false);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);

    //the following three statements are required only for HSSF
    sheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);

    //the header row: centered text in 48pt font
    Row headerRow = sheet.createRow(0);
    headerRow.setHeightInPoints(15f);
    int colNum = 0;
    Drawing drawing = sheet.createDrawingPatriarch();

    CreationHelper factory = wb.getCreationHelper();
    // When the comment box is visible, have it show in a 1x3 space
    ClientAnchor anchor = factory.createClientAnchor();
    for (ConfiguredAttribute configuredAttribute : attributes) {
        if (configuredAttribute.isVisible()) {
            Cell cell = headerRow.createCell(colNum);
            String alias = attributeAliases.get(configuredAttribute.getAttributeName());
            cell.setCellValue(alias);
            if (!alias.equals(configuredAttribute.getAttributeName())) {
                Comment comment = drawing.createCellComment(anchor);
                RichTextString str = factory.createRichTextString(configuredAttribute.getAttributeName());
                comment.setString(str);
                cell.setCellComment(comment);
            }
            cell.setCellStyle(styles.get("header"));
            sheet.autoSizeColumn(colNum);
            colNum++;
        }
    }

    //freeze the first row
    sheet.createFreezePane(0, 1);
    currentRow = 1;
}

From source file:org.alanwilliamson.openbd.plugin.spreadsheet.functions.SpreadsheetSetCellComment.java

License:Open Source License

public cfData execute(cfSession _session, List<cfData> parameters) throws cfmRunTimeException {
    if (parameters.get(2).getDataType() != cfData.CFSTRUCTDATA)
        throwException(_session, "parameter must be of type structure");

    cfSpreadSheetData spreadsheet = null;
    cfStructData commentS = null;//from  ww  w .j a  v a2s . co  m
    int rowNo, columnNo;

    /*
     * Collect up the parameters
     */
    spreadsheet = (cfSpreadSheetData) parameters.get(3);
    commentS = (cfStructData) parameters.get(2);
    rowNo = parameters.get(1).getInt() - 1;
    columnNo = parameters.get(0).getInt() - 1;

    if (rowNo < 0)
        throwException(_session, "row must be 1 or greater (" + rowNo + ")");
    if (columnNo < 0)
        throwException(_session, "column must be 1 or greater (" + columnNo + ")");

    /*
     * Perform the insertion
     */
    Sheet sheet = spreadsheet.getActiveSheet();
    Row row = sheet.getRow(rowNo);
    if (row == null)
        row = sheet.createRow(rowNo);

    Cell cell = row.getCell(columnNo);
    if (cell == null)
        cell = row.createCell(columnNo);

    // Create the anchor
    HSSFClientAnchor clientAnchor = new HSSFClientAnchor();
    if (commentS.containsKey("anchor")) {
        String[] anchor = commentS.getData("anchor").getString().split(",");
        if (anchor.length != 4)
            throwException(_session, "Invalid 'anchor' attribute, should be 4 numbers");

        clientAnchor.setRow1(Integer.valueOf(anchor[0]) - 1);
        clientAnchor.setCol1(Integer.valueOf(anchor[1]) - 1);
        clientAnchor.setRow2(Integer.valueOf(anchor[2]) - 1);
        clientAnchor.setCol2(Integer.valueOf(anchor[3]) - 1);
    } else {
        clientAnchor.setRow1(rowNo);
        clientAnchor.setCol1(columnNo);
        clientAnchor.setRow2(rowNo + 2);
        clientAnchor.setCol2(columnNo + 2);
    }

    // Create the comment
    Comment comment = spreadsheet.getActiveSheet().createDrawingPatriarch().createCellComment(clientAnchor);

    if (commentS.containsKey("author")) {
        comment.setAuthor(commentS.getData("author").getString());
    }

    if (commentS.containsKey("visible")) {
        comment.setVisible(commentS.getData("visible").getBoolean());
    }

    if (commentS.containsKey("comment")) {
        HSSFRichTextString richText = new HSSFRichTextString(commentS.getData("comment").getString());
        try {
            richText.applyFont(SpreadSheetFormatOptions.createCommentFont(spreadsheet.getWorkBook(), commentS));
        } catch (Exception e) {
            throwException(_session, e.getMessage());
        }

        comment.setString(richText);
    }

    cell.setCellComment(comment);
    return cfBooleanData.TRUE;
}

From source file:org.alanwilliamson.openbd.plugin.spreadsheet.SheetUtility.java

License:Open Source License

public static void cloneCell(Cell cNew, Cell cOld) {
    cNew.setCellComment(cOld.getCellComment());
    cNew.setCellStyle(cOld.getCellStyle());
    cNew.setCellType(cOld.getCellType());

    switch (cNew.getCellType()) {
    case Cell.CELL_TYPE_BOOLEAN: {
        cNew.setCellValue(cOld.getBooleanCellValue());
        break;/*  www. java  2 s .c o  m*/
    }
    case Cell.CELL_TYPE_NUMERIC: {
        cNew.setCellValue(cOld.getNumericCellValue());
        break;
    }
    case Cell.CELL_TYPE_STRING: {
        cNew.setCellValue(cOld.getStringCellValue());
        break;
    }
    case Cell.CELL_TYPE_ERROR: {
        cNew.setCellValue(cOld.getErrorCellValue());
        break;
    }
    case Cell.CELL_TYPE_FORMULA: {
        cNew.setCellFormula(cOld.getCellFormula());
        break;
    }
    case Cell.CELL_TYPE_BLANK: {
        cNew.setCellValue(cOld.getNumericCellValue());
        break;
    }

    }

}

From source file:org.alfresco.repo.web.scripts.DeclarativeSpreadsheetWebScript.java

License:Open Source License

/**
 * Generates the spreadsheet, based on the properties in the header
 *  and a callback for the body./* ww  w . j a v a2s  .  c  o m*/
 */
public void generateSpreadsheet(Object resource, String format, WebScriptRequest req, Status status,
        Map<String, Object> model) throws IOException {
    Pattern qnameMunger = Pattern.compile("([A-Z][a-z]+)([A-Z].*)");
    String delimiterParam = req.getParameter(PARAM_REQ_DELIMITER);
    CSVStrategy reqCSVstrategy = null;
    if (delimiterParam != null && !delimiterParam.isEmpty()) {
        reqCSVstrategy = new CSVStrategy(delimiterParam.charAt(0), '"', CSVStrategy.COMMENTS_DISABLED);
    }
    // Build up the details of the header
    List<Pair<QName, Boolean>> propertyDetails = buildPropertiesForHeader(resource, format, req);
    String[] headings = new String[propertyDetails.size()];
    String[] descriptions = new String[propertyDetails.size()];
    boolean[] required = new boolean[propertyDetails.size()];
    for (int i = 0; i < headings.length; i++) {
        Pair<QName, Boolean> property = propertyDetails.get(i);
        if (property == null || property.getFirst() == null) {
            headings[i] = "";
            required[i] = false;
        } else {
            QName column = property.getFirst();
            required[i] = property.getSecond();

            // Ask the dictionary service nicely for the details
            PropertyDefinition pd = dictionaryService.getProperty(column);
            if (pd != null && pd.getTitle(dictionaryService) != null) {
                // Use the friendly titles, which may even be localised!
                headings[i] = pd.getTitle(dictionaryService);
                descriptions[i] = pd.getDescription(dictionaryService);
            } else {
                // Nothing friendly found, try to munge the raw qname into
                //  something we can show to a user...
                String raw = column.getLocalName();
                raw = raw.substring(0, 1).toUpperCase() + raw.substring(1);

                Matcher m = qnameMunger.matcher(raw);
                if (m.matches()) {
                    headings[i] = m.group(1) + " " + m.group(2);
                } else {
                    headings[i] = raw;
                }
            }
        }
    }

    // Build a list of just the properties
    List<QName> properties = new ArrayList<QName>(propertyDetails.size());
    for (Pair<QName, Boolean> p : propertyDetails) {
        QName qn = null;
        if (p != null) {
            qn = p.getFirst();
        }
        properties.add(qn);
    }

    // Output
    if ("csv".equals(format)) {
        StringWriter sw = new StringWriter();
        CSVPrinter csv = new CSVPrinter(sw, reqCSVstrategy != null ? reqCSVstrategy : getCsvStrategy());
        csv.println(headings);

        populateBody(resource, csv, properties);

        model.put(MODEL_CSV, sw.toString());
    } else {
        Workbook wb;
        if ("xlsx".equals(format)) {
            wb = new XSSFWorkbook();
            // TODO Properties
        } else {
            wb = new HSSFWorkbook();
            // TODO Properties
        }

        // Add our header row
        Sheet sheet = wb.createSheet("Export");
        Row hr = sheet.createRow(0);
        sheet.createFreezePane(0, 1);

        Font fb = wb.createFont();
        fb.setBoldweight(Font.BOLDWEIGHT_BOLD);
        Font fi = wb.createFont();
        fi.setBoldweight(Font.BOLDWEIGHT_BOLD);
        fi.setItalic(true);

        CellStyle csReq = wb.createCellStyle();
        csReq.setFont(fb);
        CellStyle csOpt = wb.createCellStyle();
        csOpt.setFont(fi);

        // Populate the header
        Drawing draw = null;
        for (int i = 0; i < headings.length; i++) {
            Cell c = hr.createCell(i);
            c.setCellValue(headings[i]);

            if (required[i]) {
                c.setCellStyle(csReq);
            } else {
                c.setCellStyle(csOpt);
            }

            if (headings[i].length() == 0) {
                sheet.setColumnWidth(i, 3 * 250);
            } else {
                sheet.setColumnWidth(i, 18 * 250);
            }

            if (descriptions[i] != null && descriptions[i].length() > 0) {
                // Add a description for it too
                if (draw == null) {
                    draw = sheet.createDrawingPatriarch();
                }
                ClientAnchor ca = wb.getCreationHelper().createClientAnchor();
                ca.setCol1(c.getColumnIndex());
                ca.setCol2(c.getColumnIndex() + 1);
                ca.setRow1(hr.getRowNum());
                ca.setRow2(hr.getRowNum() + 2);

                Comment cmt = draw.createCellComment(ca);
                cmt.setAuthor("");
                cmt.setString(wb.getCreationHelper().createRichTextString(descriptions[i]));
                cmt.setVisible(false);
                c.setCellComment(cmt);
            }
        }

        // Have the contents populated
        populateBody(resource, wb, sheet, properties);

        // Save it for the template
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wb.write(baos);
        model.put(MODEL_EXCEL, baos.toByteArray());
    }
}

From source file:org.bbreak.excella.core.handler.DebugErrorHandler.java

License:Open Source License

/**
 * ?/* ww  w. j a va2s .  com*/
 * 
 * @param workbook 
 * @param errorCell
 * @param exception
 */
protected void markupErrorCell(Workbook workbook, ParseException exception) {
    Cell errorCell = exception.getCell();
    if (errorCell == null) {
        return;
    }
    // ????
    workbook.setActiveSheet(workbook.getSheetIndex(errorCell.getSheet()));
    errorCell.setAsActiveCell();

    if (workbook instanceof XSSFWorkbook) {
        XSSFWorkbook xssfWorkbook = (XSSFWorkbook) workbook;

        CellStyle errorCellStyle = xssfWorkbook.createCellStyle();
        errorCellStyle.setFillForegroundColor(HSSFColorPredefined.ROSE.getIndex());
        errorCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        errorCell.setCellStyle(errorCellStyle);

        // TODO:???????????????
        // XSSFComment xssfComment = ((XSSFSheet)sheet).createComment();
        // xssfComment.setRow( errorCell.getRowIndex());
        // xssfComment.setColumn( (short)errorCell.getColumnIndex());
        // XSSFRichTextString string = new XSSFRichTextString( ex.getMessage());
        // xssfComment.setString( ex.getMessage());
    } else {
        HSSFWorkbook hssfWorkbook = (HSSFWorkbook) workbook;
        int sheetNum = hssfWorkbook.getNumberOfSheets();
        for (int cnt = 0; cnt < sheetNum; cnt++) {
            hssfWorkbook.getSheetAt(cnt).setSelected(false);
        }

        // ?
        CellStyle errorCellStyle = hssfWorkbook.createCellStyle();
        errorCellStyle.setFillForegroundColor(HSSFColorPredefined.ROSE.getIndex());
        errorCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        errorCell.setCellStyle(errorCellStyle);

        // ?
        short commentColFrom = (short) (errorCell.getColumnIndex() + 1);
        short commentColTo = (short) (errorCell.getColumnIndex() + ERROR_COMENT_COL_SIZE);
        int commentRowFrom = errorCell.getRowIndex();
        int commentRowTo = errorCell.getRowIndex() + ERROR_COMENT_ROW_SIZE;

        HSSFSheet hssfSheet = (HSSFSheet) errorCell.getSheet();
        HSSFPatriarch patr = hssfSheet.createDrawingPatriarch();
        hssfSheet.setSelected(true);
        HSSFComment comment = patr.createComment(
                new HSSFClientAnchor(0, 0, 0, 0, commentColFrom, commentRowFrom, commentColTo, commentRowTo));
        comment.setVisible(true);
        comment.setString(new HSSFRichTextString(createCommentMessage(exception)));
        errorCell.setCellComment(comment);
    }
}

From source file:org.bbreak.excella.core.util.PoiUtil.java

License:Open Source License

/**
 * ?/*  www .j a  va  2s .c  o m*/
 * 
 * @param fromCell 
 * @param toCell 
 */
public static void copyCell(Cell fromCell, Cell toCell) {

    if (fromCell != null) {

        // 
        CellType cellType = fromCell.getCellTypeEnum();
        switch (cellType) {
        case BLANK:
            break;
        case FORMULA:
            String cellFormula = fromCell.getCellFormula();
            toCell.setCellFormula(cellFormula);
            break;
        case BOOLEAN:
            toCell.setCellValue(fromCell.getBooleanCellValue());
            break;
        case ERROR:
            toCell.setCellErrorValue(fromCell.getErrorCellValue());
            break;
        case NUMERIC:
            toCell.setCellValue(fromCell.getNumericCellValue());
            break;
        case STRING:
            toCell.setCellValue(fromCell.getRichStringCellValue());
            break;
        default:
        }

        // 
        if (fromCell.getCellStyle() != null
                && fromCell.getSheet().getWorkbook().equals(toCell.getSheet().getWorkbook())) {
            toCell.setCellStyle(fromCell.getCellStyle());
        }

        // 
        if (fromCell.getCellComment() != null) {
            toCell.setCellComment(fromCell.getCellComment());
        }
    }
}

From source file:org.eclipse.emfforms.internal.spreadsheet.core.renderer.EMFFormsSpreadsheetControlRenderer.java

License:Open Source License

/**
 * {@inheritDoc}/*from   w ww .ja v a 2 s  .  c  o  m*/
 *
 * @see org.eclipse.emfforms.spi.spreadsheet.core.EMFFormsAbstractSpreadsheetRenderer#render(org.apache.poi.ss.usermodel.Workbook,
 *      org.eclipse.emf.ecp.view.spi.model.VElement, org.eclipse.emf.ecp.view.spi.context.ViewModelContext,
 *      org.eclipse.emfforms.spi.spreadsheet.core.EMFFormsSpreadsheetRenderTarget)
 */
@Override
public int render(Workbook workbook, VControl vElement, ViewModelContext viewModelContext,
        EMFFormsSpreadsheetRenderTarget renderTarget) {
    Sheet sheet = workbook.getSheet(renderTarget.getSheetName());
    if (sheet == null) {
        sheet = workbook.createSheet(renderTarget.getSheetName());
        setupSheetFormat(sheet);
    }
    Row labelRow = sheet.getRow(0);
    if (labelRow == null) {
        labelRow = sheet.createRow(0);
    }
    Row descriptionRow = sheet.getRow(1);
    if (descriptionRow == null) {
        descriptionRow = sheet.createRow(1);
    }
    Row formatRow = sheet.getRow(2);
    if (formatRow == null) {
        formatRow = sheet.createRow(2);
    }

    final CellStyle readOnly = (CellStyle) viewModelContext.getContextValue(EMFFormsCellStyleConstants.LOCKED);
    final CellStyle readOnlyWrap = (CellStyle) viewModelContext
            .getContextValue(EMFFormsCellStyleConstants.LOCKED_AND_WRAPPED);

    final Cell idCell = labelRow.getCell(0, Row.CREATE_NULL_AS_BLANK);
    idCell.setCellValue(EMFFormsIdProvider.ID_COLUMN);
    idCell.setCellStyle(readOnly);

    final Cell labelCell = labelRow.getCell(renderTarget.getColumn() + 1, Row.CREATE_NULL_AS_BLANK);
    labelCell.setCellStyle(readOnlyWrap);

    final Cell descriptionCell = descriptionRow.getCell(renderTarget.getColumn() + 1, Row.CREATE_NULL_AS_BLANK);
    descriptionCell.setCellStyle(readOnlyWrap);

    final Cell formatCell = formatRow.getCell(renderTarget.getColumn() + 1, Row.CREATE_NULL_AS_BLANK);
    formatCell.setCellStyle(readOnlyWrap);

    try {
        final EMFFormsExportTableParent exportTableParent = (EMFFormsExportTableParent) viewModelContext
                .getContextValue(EMFFormsExportTableParent.EXPORT_TABLE_PARENT);
        VDomainModelReference dmrToResolve = EcoreUtil.copy(vElement.getDomainModelReference());
        if (exportTableParent != null) {
            final VIndexDomainModelReference indexDMR = exportTableParent.getIndexDMRToExtend();
            indexDMR.setTargetDMR(dmrToResolve);

            dmrToResolve = exportTableParent.getIndexDMRToResolve();
        }

        if (labelCell.getCellComment() == null) {
            final EStructuralFeature structuralFeature = emfformsDatabinding
                    .getValueProperty(dmrToResolve, viewModelContext.getDomainModel()).getStructuralFeature();

            writeLabel(vElement, viewModelContext, labelCell, exportTableParent, dmrToResolve,
                    structuralFeature);

            final Comment comment = createComment(workbook, sheet, dmrToResolve, renderTarget.getRow(),
                    renderTarget.getColumn() + 1);
            labelCell.setCellComment(comment);

            writeDescription(viewModelContext, descriptionCell, dmrToResolve);

            writeFormatInformation(formatCell, structuralFeature);
        }
        if (viewModelContext.getDomainModel() != null) {
            writeValue(viewModelContext, renderTarget, sheet, dmrToResolve);
        }

        return 1;
    } catch (final DatabindingFailedException ex) {
        reportService.report(new EMFFormsSpreadsheetReport(ex, EMFFormsSpreadsheetReport.ERROR));
    } catch (final NoLabelFoundException ex) {
        reportService.report(new EMFFormsSpreadsheetReport(ex, EMFFormsSpreadsheetReport.ERROR));
    } catch (final IOException ex) {
        reportService.report(new EMFFormsSpreadsheetReport(ex, EMFFormsSpreadsheetReport.ERROR));
    } catch (final EMFFormsConverterException ex) {
        reportService.report(new EMFFormsSpreadsheetReport(ex, EMFFormsSpreadsheetReport.ERROR));
    }

    return 0;
}