Example usage for org.apache.poi.ss.usermodel Comment setString

List of usage examples for org.apache.poi.ss.usermodel Comment setString

Introduction

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

Prototype

void setString(RichTextString string);

Source Link

Document

Sets the rich text string used by this comment.

Usage

From source file:de.enerko.reports2.engine.Report.java

License:Apache License

/**
 * This method adds a new cell to the sheet of a workbook. It could 
 * (together with {@link #fill(Workbook, Cell, String, String, boolean)}) be moved to
 * the {@link CellDefinition} itself, but that would mean that the {@link CellDefinition} is
 * tied to a specific Excel API. Having those methods here allows the Report to become
 * an interface if a second engine (i.e. JXL) should be added in the future.
 * @param workbook/*from w ww  . j a v  a 2s  .  c o  m*/
 * @param sheet
 * @param cellDefinition
 */
private void addCell(final Workbook workbook, final Sheet sheet, final CellDefinition cellDefinition) {
    final int columnNum = cellDefinition.column, rowNum = cellDefinition.row;

    Row row = sheet.getRow(rowNum);
    if (row == null)
        row = sheet.createRow(rowNum);

    Cell cell = row.getCell(columnNum);
    // If the cell already exists and is no blank cell
    // it will be used including all formating
    if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
        cell = fill(workbook, cell, cellDefinition, false);
    }
    // Otherwise a new cell will be created, the datatype set and 
    // optionally a format will be created
    else {
        cell = fill(workbook, row.createCell(columnNum), cellDefinition, true);

        final Sheet referenceSheet;
        if (cellDefinition.getReferenceCell() != null
                && (referenceSheet = workbook.getSheet(cellDefinition.getReferenceCell().sheetname)) != null) {
            final Row referenceRow = referenceSheet.getRow(cellDefinition.getReferenceCell().row);
            final Cell referenceCell = referenceRow == null ? null
                    : referenceRow.getCell(cellDefinition.getReferenceCell().column);
            if (referenceCell != null && referenceCell.getCellStyle() != null)
                cell.setCellStyle(referenceCell.getCellStyle());
        }
    }

    // Add an optional comment      
    if (cellDefinition.hasComment()) {
        final CreationHelper factory = workbook.getCreationHelper();

        final Drawing drawing = sheet.createDrawingPatriarch();
        final ClientAnchor commentAnchor = factory.createClientAnchor();

        final int col1 = cellDefinition.comment.column == null ? cell.getColumnIndex() + 1
                : cellDefinition.comment.column;
        final int row1 = cellDefinition.comment.row == null ? cell.getRowIndex() : cellDefinition.comment.row;

        commentAnchor.setCol1(col1);
        commentAnchor.setRow1(row1);
        commentAnchor.setCol2(col1 + Math.max(1, cellDefinition.comment.width));
        commentAnchor.setRow2(row1 + Math.max(1, cellDefinition.comment.height));

        final Comment comment = drawing.createCellComment(commentAnchor);
        comment.setString(factory.createRichTextString(cellDefinition.comment.text));
        comment.setAuthor(cellDefinition.comment.author);
        comment.setVisible(cellDefinition.comment.visible);

        cell.setCellComment(comment);
    }
}

From source file:de.fme.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  va 2s. 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].*)");

    // 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() != null) {
                // Use the friendly titles, which may even be localised!
                headings[i] = pd.getTitle();
                descriptions[i] = pd.getDescription();
            } 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, CSVStrategy.EXCEL_STRATEGY);
        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);
        try {
            sheet.createFreezePane(0, 1);
        } catch (IndexOutOfBoundsException e) {
            //https://issues.apache.org/bugzilla/show_bug.cgi?id=51431 & http://stackoverflow.com/questions/6469693/apache-poi-clearing-freeze-split-panes
        }
        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:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.exporter.ExportWorkbook.java

License:Open Source License

/**
 * Adds headers stored in <code>headers</code> to the current sheet. If required, a special width
 * for the corresponding column can be set by providing a value in <code>headersWidth</code> using
 * header as key.<br/>/* w  w w . ja v a2s  .com*/
 * <b>IMPORTANT</b>: Headers are added in the order provided in <code>headers</code>.
 * 
 * @param headers
 *          headers to be added
 */
public void addHeaders(int sheetId, List<ExcelSheet.Header> headers) {
    Sheet sheet = getSheetById(sheetId);
    Drawing drawing = sheet.createDrawingPatriarch();
    CreationHelper factory = sheet.getWorkbook().getCreationHelper();
    Row row = sheet.createRow(this.getCurrentRowOfSheet(sheet, 3));
    int columnIndex = 0;
    for (ExcelSheet.Header header : headers) {
        int currColumnIndex = columnIndex;
        Cell cell = row.createCell(columnIndex);
        if (header.getDescription() != null) {
            ClientAnchor commentAnchor = factory.createClientAnchor();
            //Sizing the comment 1x3 cells
            commentAnchor.setCol1(cell.getColumnIndex());
            commentAnchor.setCol2(cell.getColumnIndex() + 1);
            commentAnchor.setRow1(row.getRowNum());
            commentAnchor.setRow2(row.getRowNum() + 3);

            Comment comment = drawing.createCellComment(commentAnchor);
            RichTextString str = factory.createRichTextString(header.getDescription());
            comment.setString(str);
            comment.setAuthor("");
            cell.setCellComment(comment);
        }

        setCellValue(cell, header.getLabel(), getHeaderTableStyle());
        Integer width = header.getWidth();
        if (width != null) {
            sheet.setColumnWidth(currColumnIndex, width.intValue());
        }
        columnIndex++;
    }

    LOGGER.debug("Added headers.");
}

From source file:de.jlo.talendcomp.excel.SpreadsheetOutput.java

License:Apache License

private void setCellComment(Cell cell, String comment) {
    if (comment == null || comment.trim().isEmpty()) {
        cell.removeCellComment();/*from w w  w.  j  a  v a  2  s  . c  o  m*/
    } else {
        Comment c = cell.getCellComment();
        if (c == null) {
            ClientAnchor anchor = creationHelper.createClientAnchor();
            anchor.setRow1(cell.getRowIndex());
            anchor.setRow2(cell.getRowIndex() + commentHeight);
            anchor.setCol1(cell.getColumnIndex() + 1);
            anchor.setCol2(cell.getColumnIndex() + commentWidth + 1);
            anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE);
            c = getDrawing().createCellComment(anchor);
            c.setVisible(false);
            if (commentAuthor != null) {
                c.setAuthor(commentAuthor);
            }
            cell.setCellComment(c);
        }
        RichTextString rts = creationHelper.createRichTextString(comment);
        c.setString(rts);
    }
}

From source file:de.viaboxx.nlstools.formats.MBExcelPersistencer.java

License:Apache License

private Comment comment(HSSFCell cell, String text) {
    CreationHelper factory = wb.getCreationHelper();
    Drawing drawing = sheet.createDrawingPatriarch();
    // When the comment box is visible, have it show in a 1x3 space
    ClientAnchor anchor = factory.createClientAnchor();
    anchor.setCol1(cell.getColumnIndex());
    anchor.setCol2(cell.getColumnIndex() + 1);
    anchor.setRow1(cell.getRow().getRowNum());
    anchor.setRow2(cell.getRow().getRowNum() + 3);
    Comment comment = drawing.createCellComment(anchor);
    RichTextString str = factory.createRichTextString(text);
    comment.setString(str);
    cell.setCellComment(comment);/*from  w ww  . j ava 2  s.  co  m*/
    return comment;
}

From source file:excel.CellComments.java

License:Apache License

public static void main(String[] args) throws IOException {
    try (Workbook wb = new XSSFWorkbook()) {

        CreationHelper factory = wb.getCreationHelper();

        Sheet sheet = wb.createSheet();//from  w w  w.  jav a 2s .co m

        Cell cell1 = sheet.createRow(3).createCell(5);
        cell1.setCellValue("F4");

        Drawing<?> drawing = sheet.createDrawingPatriarch();

        ClientAnchor anchor = factory.createClientAnchor();

        Comment comment1 = drawing.createCellComment(anchor);
        RichTextString str1 = factory.createRichTextString("Hello, World!");
        comment1.setString(str1);
        comment1.setAuthor("Apache POI");
        cell1.setCellComment(comment1);

        Cell cell2 = sheet.createRow(2).createCell(2);
        cell2.setCellValue("C3");

        Comment comment2 = drawing.createCellComment(anchor);
        RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");
        //apply custom font to the text in the comment
        Font font = wb.createFont();
        font.setFontName("Arial");
        font.setFontHeightInPoints((short) 14);
        font.setBold(true);
        font.setColor(IndexedColors.RED.getIndex());
        str2.applyFont(font);

        comment2.setString(str2);
        comment2.setAuthor("Apache POI");
        comment2.setAddress(new CellAddress("C3"));

        try (FileOutputStream out = new FileOutputStream("comments.xlsx")) {
            wb.write(out);
        }
    }
}

From source file:excel.PoiWriteExcelFile.java

public static int generarReporte() {

    //Calendar cal=Calendar.getInstance();
    Calendar cal = WorkMonitorUI.instante;

    try {/*from w w  w  .j a va2s .c o  m*/
        FileOutputStream fileOut = new FileOutputStream("HH_"
                + instante.getDisplayName(Calendar.MONTH, Calendar.SHORT_FORMAT, Locale.getDefault())
                        .toUpperCase()
                + "_" + persona.getNombre().toUpperCase().charAt(0) + "." + persona.getApellido().toUpperCase()
                + "_" + instante.get(Calendar.YEAR) + ".xls");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet worksheet = workbook.createSheet(
                cal.getDisplayName(Calendar.MONTH, Calendar.SHORT_FORMAT, Locale.getDefault()).toUpperCase()
                        + "-" + cal.get(Calendar.YEAR));

        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        font.setFontName("Calibri");
        font.setItalic(false);
        font.setBold(true);
        font.setColor(HSSFColor.BLACK.index);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle diasStyle = workbook.createCellStyle();
        diasStyle.setFillForegroundColor(HSSFColor.SEA_GREEN.index);
        diasStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        font = workbook.createFont();
        font.setFontHeightInPoints((short) 11);
        font.setFontName("Calibri");
        font.setItalic(false);
        font.setBold(true);
        font.setColor(HSSFColor.WHITE.index);
        diasStyle.setFont(font);
        diasStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        diasStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        diasStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        diasStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        diasStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        diasStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle schedStyle = workbook.createCellStyle();
        schedStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        schedStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        HSSFFont font3 = workbook.createFont();
        font3.setFontHeightInPoints((short) 11);
        font3.setFontName("Calibri");
        font3.setItalic(false);
        font3.setColor(HSSFColor.BLACK.index);
        schedStyle.setFont(font3);
        schedStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        schedStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        schedStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        schedStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        schedStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        schedStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle workdayStyle = workbook.createCellStyle();
        //workdayStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);                        
        workdayStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        workdayStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        workdayStyle.setWrapText(true);
        HSSFFont font2 = workbook.createFont();
        font2.setFontHeightInPoints((short) 8);
        font2.setFontName("Serif");
        font2.setItalic(false);
        //font2.setColor(HSSFColor.YELLOW.index);
        workdayStyle.setFont(font2);
        workdayStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle weekendStyle = workbook.createCellStyle();
        weekendStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        weekendStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        weekendStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        weekendStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        weekendStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        weekendStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        weekendStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        weekendStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle horarioStyle = workbook.createCellStyle();
        horarioStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        horarioStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        horarioStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        horarioStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        horarioStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        HSSFFont font4 = workbook.createFont();
        font4.setFontHeightInPoints((short) 10);
        font4.setFontName("Serif");
        font4.setItalic(false);
        font4.setBold(true);
        //font2.setColor(HSSFColor.YELLOW.index);
        horarioStyle.setFont(font4);

        // index from 0,0... cell A1 is cell(0,0)
        HSSFRow row1 = worksheet.createRow((short) 0);
        row1.setHeight((short) 500);

        //System.out.println("cal.get(Calendar.YEAR)="+cal.get(Calendar.YEAR));

        HSSFCell cellA1 = row1.createCell((short) 0);
        cellA1.setCellValue(
                cal.getDisplayName(Calendar.MONTH, Calendar.SHORT_FORMAT, Locale.getDefault()).toUpperCase()
                        + "-" + cal.get(Calendar.YEAR));
        cellA1.setCellStyle(cellStyle);

        HSSFRow row2 = worksheet.createRow((short) 1);
        HSSFCell cellA4 = row2.createCell((short) 0);
        cellA4.setCellValue("Horario");
        cellA4.setCellStyle(horarioStyle);
        //row2.setHeight((short)500);

        HSSFRow row3 = worksheet.createRow((short) 2);
        HSSFCell cellA3 = row3.createCell((short) 0);
        cellA3.setCellValue("Inicio - Trmino");
        cellA3.setCellStyle(diasStyle);

        Calendar hora = Calendar.getInstance();

        hora.set(Calendar.HOUR_OF_DAY, 9);
        hora.set(Calendar.MINUTE, 0);
        hora.set(Calendar.SECOND, 0);

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

        HSSFCell cellXn;

        for (int i = 0; i < 29; ++i) {
            HSSFRow row = worksheet.createRow((short) i + 3);
            row.setHeight((short) 500);

            cellXn = row.createCell((short) 0);
            String horaIni = sdf.format(hora.getTime());
            hora.add(Calendar.MINUTE, 30);
            String horaFin = sdf.format(hora.getTime());
            cellXn.setCellValue(horaIni + " - " + horaFin);
            cellXn.setCellStyle(schedStyle);
        }

        System.out.println("cal.get(Calendar.MONTH)1=" + cal.get(Calendar.MONTH));

        cal.add(Calendar.DAY_OF_MONTH, -cal.get(Calendar.DAY_OF_MONTH) + 1);

        int diasMes = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

        System.out.println("cal.get(Calendar.MONTH)2=" + cal.get(Calendar.MONTH));

        sdf = new SimpleDateFormat("EEEE d");

        System.out.println(
                "cal.getActualMaximum(Calendar.DAY_OF_MONTH)1=" + cal.getActualMaximum(Calendar.DAY_OF_MONTH));

        for (int i = 0; i < diasMes; ++i) {
            cellXn = row2.createCell((short) i + 1);
            String dia = sdf.format(cal.getTime());
            dia = Character.toUpperCase(dia.charAt(0)) + dia.substring(1);
            cellXn.setCellValue(dia);
            cellXn.setCellStyle(horarioStyle);
            //System.out.println("cal.get(Calendar.DAY_OF_MONTH)="+cal.get(Calendar.DAY_OF_MONTH));
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }

        for (int i = 0; i < diasMes; ++i) {
            cellXn = row3.createCell((short) i + 1);
            cellXn.setCellValue("Descripcin");
            cellXn.setCellStyle(diasStyle);
        }

        System.out.println(
                "cal.getActualMaximum(Calendar.DAY_OF_MONTH)2=" + cal.getActualMaximum(Calendar.DAY_OF_MONTH));

        // Retroceder mes para que quede como estaba
        cal.add(Calendar.MONTH, -1);
        //cal.add(Calendar.DAY_OF_MONTH, -1);    

        System.out.println(
                "cal.getActualMaximum(Calendar.DAY_OF_MONTH)3=" + cal.getActualMaximum(Calendar.DAY_OF_MONTH));

        HhDao hhDao = new HhDao();
        Object[][] hh = new Object[29][cal.getActualMaximum(Calendar.DAY_OF_MONTH)];

        hh = hhDao.getByMes(WorkMonitorUI.persona.getId(), cal.getTime());

        cal.set(Calendar.DAY_OF_MONTH, 1);

        Sheet sheet = workbook.getSheetAt(0);

        sdf = new SimpleDateFormat("EEEE");

        HSSFPatriarch _drawing = (HSSFPatriarch) sheet.createDrawingPatriarch();
        CreationHelper factory = workbook.getCreationHelper();

        for (int i = 0; i < 29; ++i) {
            Row r = sheet.getRow(i + 3);
            for (int j = 0; j < diasMes; ++j) {
                if (hh[i][j].toString() != "") {
                    cellXn = (HSSFCell) r.createCell((short) j + 1);
                    Hh _hh = (Hh) hh[i][j];
                    cellXn.setCellValue(
                            _hh.getTarea().getNombre().trim() + ": " + _hh.getActividad().getNombre().trim());

                    HSSFAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5);
                    org.apache.poi.ss.usermodel.Comment comment = _drawing.createComment(anchor);
                    String comentario = _hh.getTarea().getComentario().toLowerCase();
                    if (_hh.getComentario() != null)
                        comentario = comentario + _hh.getComentario().toLowerCase();
                    RichTextString str = factory.createRichTextString(comentario);

                    comment.setString(str);

                    cellXn.setCellComment(comment);
                } else {
                    cellXn = (HSSFCell) r.createCell((short) j + 1);
                    cellXn.setCellValue("");
                }
                //System.out.println("sdf.format(cal.getTime())="+sdf.format(cal.getTime()));
                if (Arrays.asList("sbado", "domingo").contains(sdf.format(cal.getTime())))
                    cellXn.setCellStyle(weekendStyle);
                else
                    cellXn.setCellStyle(workdayStyle);
                sheet.setColumnWidth(j, 5000);

                cal.add(Calendar.DAY_OF_MONTH, 1);
                //sheet.autoSizeColumn(j);
            }
            // Retroceder mes para que quede como estaba                
            cal.add(Calendar.MONTH, -1);
            System.out.println("cal.get(Calendar.MONTH)3=" + cal.get(Calendar.MONTH));
            cal.set(Calendar.DAY_OF_MONTH, 1);
        }
        sheet.setColumnWidth(diasMes, 5000);

        WorkMonitorUI.instante = Calendar.getInstance();
        sheet.setColumnWidth(0, 5000);
        sheet.createFreezePane(1, 3);
        // Freeze just one row
        //sheet.createFreezePane( 0, 1, 0, 1 );

        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return -1;
    } catch (IOException e) {
        e.printStackTrace();
        return -2;
    }
    return 1;
}

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;/*w  w  w. j a v  a 2s  . c o m*/
    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:net.ceos.project.poi.annotated.core.CellStyleHandler.java

License:Apache License

/**
 * Apply the cell comment to a cell./*w w w . j av a  2s  .  c  o  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);/* w ww .j a  va 2s.  c  o  m*/

    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;
}