Example usage for org.apache.poi.ss.usermodel DataFormat getFormat

List of usage examples for org.apache.poi.ss.usermodel DataFormat getFormat

Introduction

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

Prototype

String getFormat(short index);

Source Link

Document

get the format string that matches the given format index

Usage

From source file:com.project.jsica.cdi.ReporteBean.java

public void reporte2(List<ReportePermisoBean> reporte) {
    LOG.info("TAMAO reporte: " + reporte.size());
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    HSSFWorkbook libro = new HSSFWorkbook();

    HSSFFont fuente = libro.createFont();
    fuente.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    HSSFCellStyle estiloCeldaCabecera = libro.createCellStyle();
    estiloCeldaCabecera.setFont(fuente);
    estiloCeldaCabecera.setAlignment(HSSFCellStyle.ALIGN_CENTER);

    DataFormat format = libro.createDataFormat();

    HSSFCellStyle style = libro.createCellStyle();
    style.setDataFormat(format.getFormat("hh:mm:ss"));

    HSSFCellStyle fechas = libro.createCellStyle();
    fechas.setDataFormat(format.getFormat("dd.MM.yyyy"));

    HSSFSheet hoja = libro.createSheet("hoja 1");

    //CREAR LAS CABECERAS
    String[] cabeceras = { "CODIGO", "NOMBRE", "HORA INICIO", "HORA FIN", "HORAS", "MINUTOS", "FECHA",
            "MOTIVO" };

    HSSFRow filaCabecera = hoja.createRow(0);

    for (int x = 0; x < cabeceras.length; x++) {
        HSSFCell cabecera = filaCabecera.createCell(x);
        cabecera.setCellValue(cabeceras[x]);
        cabecera.setCellStyle(estiloCeldaCabecera);
    }/* w  ww . j a  v  a 2  s  .  c o  m*/
    //FIN DE CABECERAS
    for (int i = 0; i < reporte.size(); i++) {

        HSSFRow fila = hoja.createRow(i + 1);

        HSSFCell columna1 = fila.createCell(0);
        columna1.setCellValue(reporte.get(i).getCodigo());

        HSSFCell columna2 = fila.createCell(1);
        columna2.setCellValue(reporte.get(i).getNombre());

        HSSFCell columna3 = fila.createCell(2);
        columna3.setCellValue(reporte.get(i).getHoraInicio());
        columna3.setCellStyle(style);

        HSSFCell columna4 = fila.createCell(3);
        columna4.setCellValue(reporte.get(i).getHoraFin());
        columna4.setCellStyle(style);

        HSSFCell columna5 = fila.createCell(4);
        columna5.setCellValue(reporte.get(i).getHoras());

        HSSFCell columna6 = fila.createCell(5);
        columna6.setCellValue(reporte.get(i).getMinutos());

        HSSFCell columna7 = fila.createCell(6);
        columna7.setCellValue(reporte.get(i).getFechaReal());
        columna7.setCellStyle(fechas);

        HSSFCell columna8 = fila.createCell(7);
        columna8.setCellValue(reporte.get(i).getMotivo());
    }

    try {

        OutputStream output = response.getOutputStream();

        libro.write(output);
        output.close();

        fc.responseComplete();

    } catch (IOException ex) {
        LOG.info("ERROR: " + ex);
    }
}

From source file:com.project.jsica.cdi.ReporteBean.java

public void reporte3() {
    if (nuevoReporte) {
        LOG.info("OPCION: " + opcionReporte);
        String nombreReporte = "";
        int filas = 0;
        if (opcionReporte == 2) {
            reporte = registroAsistenciaController.buscarXArea(areaSeleccionada, desde, hasta);
            LOG.info("TAMAO reporte: " + reporte.size());
            nombreReporte = "Reporte de asistencia por area";
            filas = 1;//ww w .j a  v  a 2 s .  c om
        } else if (opcionReporte == 1) {
            reporte = registroAsistenciaController.buscarXEmpleado(empleado, desde, hasta);
            LOG.info("TAMAO reporte: " + reporte.size());
            nombreReporte = "Reporte de asistencia por empleado";
            filas = 0;
        }

        FacesContext fc = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + nombreReporte + ".xls");

        HSSFWorkbook libro = new HSSFWorkbook();

        HSSFFont fuente = libro.createFont();
        fuente.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        HSSFCellStyle estiloCeldaCabecera = libro.createCellStyle();
        estiloCeldaCabecera.setFont(fuente);
        estiloCeldaCabecera.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        DataFormat format = libro.createDataFormat();

        HSSFCellStyle style = libro.createCellStyle();
        style.setDataFormat(format.getFormat("hh:mm:ss"));

        HSSFCellStyle fechas = libro.createCellStyle();
        fechas.setDataFormat(format.getFormat("dd.MM.yyyy"));

        HSSFSheet hoja = libro.createSheet("Reporte de Asistencias");

        //CREAR LAS CABECERAS
        String[] cabeceras = { "CODIGO", "APELLIDOS Y NOMBRES", "FECHA", "TIPO", "HORA DE INGRESO",
                "HORA DE SALIDA", "MARCACION DE ENTRADA", "MARCACION DE SALIDA", "TARDANZA(Minutos)",
                "SALIDA REFRIGERIO", "ENTRADA REFRIGERIO", "MARCACION SALIDA R", "MARCACION DE ENTRADA R",
                "TARDANZA(refrigerio)", "TARDANZA TOTAL" };

        if (filas == 1) {
            HSSFRow filaArea = hoja.createRow(0);
            HSSFCell Area = filaArea.createCell(0);
            Area.setCellValue("AREA");
            Area.setCellStyle(estiloCeldaCabecera);

            HSSFCell nombre = filaArea.createCell(1);
            nombre.setCellValue(areaSeleccionada.getNombre() + "");
        }

        HSSFRow filaCabecera = hoja.createRow(filas);

        for (int x = 0; x < cabeceras.length; x++) {
            HSSFCell cabecera = filaCabecera.createCell(x);
            cabecera.setCellValue(cabeceras[x]);
            cabecera.setCellStyle(estiloCeldaCabecera);
        }
        //FIN DE CABECERAS
        for (int i = filas; i < reporte.size(); i++) {

            HSSFRow fila = hoja.createRow(i + 1);

            HSSFCell columna1 = fila.createCell(0);
            columna1.setCellValue(reporte.get(i).getEmpleado().getCodigo());

            HSSFCell columna2 = fila.createCell(1);
            columna2.setCellValue(reporte.get(i).getEmpleado().getNombreCompleto());

            HSSFCell columna3 = fila.createCell(2);
            columna3.setCellValue(reporte.get(i).getFecha());
            columna3.setCellStyle(fechas);

            HSSFCell columna4 = fila.createCell(3);
            columna4.setCellValue(reporte.get(i).getTipo() + "");

            HSSFCell columna5 = fila.createCell(4);
            columna5.setCellValue(reporte.get(i).getHoraEntrada());
            columna5.setCellStyle(style);

            HSSFCell columna6 = fila.createCell(5);
            columna6.setCellValue(reporte.get(i).getHoraSalida());
            columna6.setCellStyle(style);

            HSSFCell columna7 = fila.createCell(6);
            if (reporte.get(i).getMarcacionInicio() != null) {
                columna7.setCellValue(reporte.get(i).getMarcacionInicio());
                columna7.setCellStyle(style);
            } else {
                columna7.setCellValue("No marco.");
            }

            HSSFCell columna8 = fila.createCell(7);
            if (reporte.get(i).getMarcacionFin() != null) {
                columna8.setCellValue(reporte.get(i).getMarcacionFin());
                columna8.setCellStyle(style);
            } else {
                columna8.setCellValue("No marco.");
            }

            HSSFCell columna9 = fila.createCell(8);
            int minutos = (int) ((reporte.get(i).getMilisTardanzaTotal() / (1000 * 60)) % 60);
            columna9.setCellValue(minutos);

            HSSFCell columna10 = fila.createCell(9);
            columna10.setCellValue(reporte.get(i).getHoraSalidaRefrigerio());
            columna10.setCellStyle(style);

            HSSFCell columna11 = fila.createCell(10);
            columna11.setCellValue(reporte.get(i).getHoraEntradaRefrigerio());
            columna11.setCellStyle(style);

            HSSFCell columna12 = fila.createCell(11);
            if (reporte.get(i).getMarcacionInicioRefrigerio() != null) {
                columna12.setCellValue(reporte.get(i).getMarcacionInicioRefrigerio());
                columna12.setCellStyle(style);
            } else {
                columna12.setCellValue("No marco.");
            }

            HSSFCell columna13 = fila.createCell(12);
            if (reporte.get(i).getMarcacionFinRefrigerio() != null) {
                columna13.setCellValue(reporte.get(i).getMarcacionFinRefrigerio());
                columna13.setCellStyle(style);
            } else {
                columna13.setCellValue("No marco.");
            }

            HSSFCell columna14 = fila.createCell(13);
            columna14.setCellValue((int) ((reporte.get(i).getMilisTardanzaRefrigerio() / (1000 * 60)) % 60));

            HSSFCell columna15 = fila.createCell(14);
            columna15.setCellValue((int) ((reporte.get(i).getMilisTardanzaTotalFinal() / (1000 * 60)) % 60));

        }

        try {
            OutputStream output = response.getOutputStream();

            libro.write(output);
            output.close();

            fc.responseComplete();
        } catch (IOException ex) {
            LOG.info("ERROR: " + ex);
        }

        nuevoReporte = false;
    }

}

From source file:com.quanticate.opensource.datalistdownload.DataListDownloadWebScript.java

License:Open Source License

@Override
protected void populateBody(Object resource, Workbook workbook, Sheet sheet, List<QName> properties)
        throws IOException {
    NodeRef list = (NodeRef) resource;//w ww. j a  v  a 2 s .  com
    List<NodeRef> items = getItems(list);

    // Our various formats
    DataFormat formatter = workbook.createDataFormat();

    CellStyle styleInt = workbook.createCellStyle();
    styleInt.setDataFormat(formatter.getFormat("0"));
    CellStyle styleDate = workbook.createCellStyle();
    styleDate.setDataFormat(formatter.getFormat("yyyy-mm-dd"));
    CellStyle styleDouble = workbook.createCellStyle();
    styleDouble.setDataFormat(formatter.getFormat("General"));
    CellStyle styleNewLines = workbook.createCellStyle();
    styleNewLines.setWrapText(true);

    // Export the items
    int rowNum = 1, colNum = 0;
    for (NodeRef item : items) {
        Row r = sheet.createRow(rowNum);

        colNum = 0;
        for (QName prop : properties) {
            Cell c = r.createCell(colNum);

            Pair<Object, String> valAndLink = identifyValueAndLink(item, prop);

            if (valAndLink == null) {
                // This property isn't set
                c.setCellType(Cell.CELL_TYPE_BLANK);
            } else {
                Object val = valAndLink.getFirst();

                // Multi-line property?
                if (val instanceof String[]) {
                    String[] lines = (String[]) val;
                    StringBuffer text = new StringBuffer();

                    for (String line : lines) {
                        if (text.length() > 0) {
                            text.append('\n');
                        }
                        text.append(line);
                    }

                    String v = text.toString();
                    c.setCellValue(v);
                    if (lines.length > 1) {
                        c.setCellStyle(styleNewLines);
                        r.setHeightInPoints(lines.length * sheet.getDefaultRowHeightInPoints());
                    }
                }

                // Regular properties
                else if (val instanceof String) {
                    c.setCellValue((String) val);
                } else if (val instanceof Date) {
                    c.setCellValue((Date) val);
                    c.setCellStyle(styleDate);
                } else if (val instanceof Integer || val instanceof Long) {
                    double v = 0.0;
                    if (val instanceof Long)
                        v = (double) (Long) val;
                    if (val instanceof Integer)
                        v = (double) (Integer) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleInt);
                } else if (val instanceof Float || val instanceof Double) {
                    double v = 0.0;
                    if (val instanceof Float)
                        v = (double) (Float) val;
                    if (val instanceof Double)
                        v = (double) (Double) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleDouble);
                } else {
                    // TODO
                    System.err
                            .println("TODO: Handle Excel output of " + val.getClass().getName() + " - " + val);
                }
            }

            colNum++;
        }

        rowNum++;
    }

    // Sensible column widths please!
    colNum = 0;
    for (QName prop : properties) {
        sheet.autoSizeColumn(colNum);
        colNum++;
    }
}

From source file:com.sccl.attech.common.utils.excel.ExportExcel.java

License:Open Source License

/**
 * ?//from ww w  .  j  a v a2s.  c  om
 * @param row 
 * @param column ?
 * @param val 
 * @param align ??1?23??
 * @return ?
 */
public Cell addCellStyle(Row row, int column, Object val, int align, Class<?> fieldType) {
    Cell cell = row.createCell(column);
    CellStyle style = styles.get("data" + (align >= 1 && align <= 3 ? align : ""));
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
    style.setWrapText(true);
    try {
        if (val == null) {
            cell.setCellValue("");
        } else if (val instanceof String) {
            cell.setCellValue((String) val);
        } else if (val instanceof Integer) {
            cell.setCellValue((Integer) val);
        } else if (val instanceof Long) {
            cell.setCellValue((Long) val);
        } else if (val instanceof Double) {
            cell.setCellValue((Double) val);
        } else if (val instanceof Float) {
            cell.setCellValue((Float) val);
        } else if (val instanceof Date) {
            DataFormat format = wb.createDataFormat();
            style.setDataFormat(format.getFormat("yyyy-MM-dd"));
            cell.setCellValue((Date) val);
        } else {
            if (fieldType != Class.class) {
                cell.setCellValue((String) fieldType.getMethod("setValue", Object.class).invoke(null, val));
            } else {
                cell.setCellValue((String) Class
                        .forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
                                "fieldtype." + val.getClass().getSimpleName() + "Type"))
                        .getMethod("setValue", Object.class).invoke(null, val));
            }
        }
    } catch (Exception ex) {
        log.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString());
        cell.setCellValue(val.toString());
    }
    if (column == 8) {
        CellRangeAddressList regions = new CellRangeAddressList(25, 25, 8, 8);
        // ?  
        DVConstraint constraint = DVConstraint
                .createExplicitListConstraint(new String[] { "2", "3", "" });
        //   
        HSSFDataValidation data_validation = new HSSFDataValidation(regions, constraint);
        // sheet  
        data_validation.createErrorBox("Error", "Error");
        data_validation.createPromptBox("", null);
        sheet.addValidationData(data_validation);
    }
    cell.setCellStyle(style);
    return cell;
}

From source file:com.toolsverse.etl.connector.excel.ExcelConnector.java

License:Open Source License

@SuppressWarnings("resource")
public void prePersist(ExcelConnectorParams params, DataSet dataSet, Driver driver) throws Exception {
    String fileName = null;/*  w w  w.  ja v  a2  s.  c  o  m*/

    OutputStream out = null;

    if (params.getOutputStream() == null) {
        fileName = SystemConfig.instance().getPathUsingAppFolders(params.getFileName(
                dataSet.getOwnerName() != null ? dataSet.getOwnerName() : dataSet.getName(), ".xls", true));

        params.setRealFileName(fileName);

        out = new FileOutputStream(fileName);

        if (params.getTransactionMonitor() != null)
            params.getTransactionMonitor().addFile(fileName);
    } else
        out = params.getOutputStream();

    params.setOut(out);

    Workbook workbook = new HSSFWorkbook();

    params.setWorkbook(workbook);

    Sheet sheet = workbook
            .createSheet(Utils.isNothing(params.getSheetName()) ? dataSet.getName() : params.getSheetName());

    params.setSheet(sheet);

    Font labelFont = workbook.createFont();
    labelFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    CellStyle labelCellStyle = workbook.createCellStyle();
    labelCellStyle.setFont(labelFont);

    DataFormat dateTimeFormat = workbook.createDataFormat();
    CellStyle dateTimeCellStyle = workbook.createCellStyle();
    dateTimeCellStyle.setDataFormat(dateTimeFormat.getFormat(params.getDateTimeFormat()));

    params.setDateTimeCellStyle(dateTimeCellStyle);

    DataFormat dateFormat = workbook.createDataFormat();
    CellStyle dateCellStyle = workbook.createCellStyle();
    dateCellStyle.setDataFormat(dateFormat.getFormat(params.getDateFormat()));

    params.setDateCellStyle(dateCellStyle);

    DataFormat timeFormat = workbook.createDataFormat();
    CellStyle timeCellStyle = workbook.createCellStyle();
    timeCellStyle.setDataFormat(timeFormat.getFormat(params.getTimeFormat()));

    params.setTimeCellStyle(timeCellStyle);

    // column names
    Row excelRow = sheet.createRow(0);

    // metadata
    int col = 0;
    for (FieldDef fieldDef : dataSet.getFields().getList()) {
        if (!fieldDef.isVisible())
            continue;

        Cell labelCell = excelRow.createCell(col++, Cell.CELL_TYPE_STRING);
        labelCell.setCellStyle(labelCellStyle);
        labelCell.setCellValue(fieldDef.getName());
    }

    params.setPrePersistOccured(true);
}

From source file:com.toolsverse.etl.connector.excel.ExcelXlsxConnector.java

License:Open Source License

@SuppressWarnings("resource")
public void prePersist(ExcelConnectorParams params, DataSet dataSet, Driver driver) throws Exception {
    String fileName = null;//from   www  .java  2 s .  c  o  m

    OutputStream out = null;

    if (params.getOutputStream() == null) {
        fileName = SystemConfig.instance().getPathUsingAppFolders(params.getFileName(
                dataSet.getOwnerName() != null ? dataSet.getOwnerName() : dataSet.getName(), ".xlsx", true));

        params.setRealFileName(fileName);

        out = new FileOutputStream(fileName);

        if (params.getTransactionMonitor() != null)
            params.getTransactionMonitor().addFile(fileName);
    } else
        out = params.getOutputStream();

    params.setOut(out);

    Workbook workbook = new SXSSFWorkbook(100);

    params.setWorkbook(workbook);

    Sheet sheet = workbook
            .createSheet(Utils.isNothing(params.getSheetName()) ? dataSet.getName() : params.getSheetName());

    params.setSheet(sheet);

    Font labelFont = workbook.createFont();
    labelFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    CellStyle labelCellStyle = workbook.createCellStyle();
    labelCellStyle.setFont(labelFont);

    DataFormat dateTimeFormat = workbook.createDataFormat();
    CellStyle dateTimeCellStyle = workbook.createCellStyle();
    dateTimeCellStyle.setDataFormat(dateTimeFormat.getFormat(params.getDateTimeFormat()));

    params.setDateTimeCellStyle(dateTimeCellStyle);

    DataFormat dateFormat = workbook.createDataFormat();
    CellStyle dateCellStyle = workbook.createCellStyle();
    dateCellStyle.setDataFormat(dateFormat.getFormat(params.getDateFormat()));

    params.setDateCellStyle(dateCellStyle);

    DataFormat timeFormat = workbook.createDataFormat();
    CellStyle timeCellStyle = workbook.createCellStyle();
    timeCellStyle.setDataFormat(timeFormat.getFormat(params.getTimeFormat()));

    params.setTimeCellStyle(timeCellStyle);

    // column names
    Row excelRow = sheet.createRow(0);

    // metadata
    int col = 0;
    for (FieldDef fieldDef : dataSet.getFields().getList()) {
        if (!fieldDef.isVisible())
            continue;

        Cell labelCell = excelRow.createCell(col++);
        labelCell.setCellStyle(labelCellStyle);
        labelCell.setCellValue(fieldDef.getName());
    }

    params.setPrePersistOccured(true);
}

From source file:csv.impl.DefaultExcelFormatter.java

License:Open Source License

/**
 * Returns the ID of the format or creates a new one if required.
 * @param writer writer that provides the workbook
 * @param format format to be used//  w  ww.  j a va 2 s  . com
 * @return ID of format
 */
protected Short getIntegerFormat(ExcelWriter writer, String format) {
    Short rc = intFormat.get(format);
    if (rc == null) {
        DataFormat formatHelper = writer.getWorkbook().createDataFormat();
        rc = formatHelper.getFormat(format);
        intFormat.put(format, rc);
    }
    return rc;
}

From source file:csv.impl.DefaultExcelFormatter.java

License:Open Source License

/**
 * Returns the ID of the format or creates a new one if required.
 * @param writer writer that provides the workbook
 * @param format format to be used//  w  w  w .  j av a  2s.  com
 * @return ID of format
 */
protected Short getRealFormat(ExcelWriter writer, String format) {
    Short rc = intFormat.get(format);
    if (rc == null) {
        DataFormat formatHelper = writer.getWorkbook().createDataFormat();
        rc = formatHelper.getFormat(format);
        realFormat.put(format, rc);
    }
    return rc;
}

From source file:de.fme.alfresco.repo.web.scripts.datalist.DataListDownloadWebScript.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override//from   ww  w. j av a 2  s.  c om
protected void populateBody(Object resource, Workbook workbook, Sheet sheet, List<QName> properties)
        throws IOException {
    NodeRef list = (NodeRef) resource;
    List<NodeRef> items = getItems(list);

    // Our various formats
    DataFormat formatter = workbook.createDataFormat();
    CreationHelper createHelper = workbook.getCreationHelper();

    CellStyle styleInt = workbook.createCellStyle();
    styleInt.setDataFormat(formatter.getFormat("0"));
    CellStyle styleDate = workbook.createCellStyle();
    styleDate.setDataFormat(formatter.getFormat("yyyy-mm-dd"));
    CellStyle styleDouble = workbook.createCellStyle();
    styleDouble.setDataFormat(formatter.getFormat("General"));
    CellStyle styleNewLines = workbook.createCellStyle();
    styleNewLines.setWrapText(true);

    CellStyle hlink_style = workbook.createCellStyle();
    Font hlink_font = workbook.createFont();
    hlink_font.setUnderline(Font.U_SINGLE);
    hlink_font.setColor(IndexedColors.BLUE.getIndex());
    hlink_style.setFont(hlink_font);

    // Export the items
    int rowNum = 1, colNum = 0;
    for (NodeRef item : items) {
        Row r = sheet.createRow(rowNum);

        colNum = 0;
        for (QName prop : properties) {
            Cell c = r.createCell(colNum);

            Serializable val = nodeService.getProperty(item, prop);
            if (val == null) {
                // Is it an association, or just missing?
                List<AssociationRef> assocs = nodeService.getTargetAssocs(item, prop);
                Set<QName> qnames = new HashSet<QName>(1, 1.0f);
                qnames.add(prop);
                List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(item, qnames);
                if (assocs.size() > 0) {
                    StringBuffer text = new StringBuffer();
                    int lines = 1;

                    for (AssociationRef ref : assocs) {
                        NodeRef child = ref.getTargetRef();
                        QName type = nodeService.getType(child);
                        if (ContentModel.TYPE_PERSON.equals(type)) {
                            if (text.length() > 0) {
                                text.append('\n');
                                lines++;
                            }
                            text.append(nodeService.getProperty(child, ContentModel.PROP_FIRSTNAME));
                            text.append(" ");
                            text.append(nodeService.getProperty(child, ContentModel.PROP_LASTNAME));
                        } else if (ContentModel.TYPE_CONTENT.equals(type)) {
                            // TODO Link to the content
                            if (text.length() > 0) {
                                text.append('\n');
                                lines++;
                            }
                            text.append(nodeService.getProperty(child, ContentModel.PROP_NAME));
                            text.append(" (");
                            text.append(nodeService.getProperty(child, ContentModel.PROP_TITLE));
                            text.append(") ");
                            /*MessageFormat.format(CONTENT_DOWNLOAD_PROP_URL, new Object[] {
                                    child.getStoreRef().getProtocol(),
                                    child.getStoreRef().getIdentifier(),
                                    child.getId(),
                                    URLEncoder.encode((String)nodeService.getProperty(child, ContentModel.PROP_TITLE)),
                                    URLEncoder.encode(ContentModel.PROP_CONTENT.toString()) });
                            */
                            /*currently only one link per cell possible
                             * Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
                             *link.setAddress("http://poi.apache.org/");
                             *c.setHyperlink(link);
                             *c.setCellStyle(hlink_style);*/
                        } else if (ApplicationModel.TYPE_FILELINK.equals(type)) {
                            NodeRef linkRef = (NodeRef) nodeService.getProperty(child,
                                    ContentModel.PROP_LINK_DESTINATION);
                            if (linkRef != null) {
                                if (text.length() > 0) {
                                    text.append('\n');
                                    lines++;
                                }
                                text.append("link to: ");
                                try {
                                    text.append(nodeService.getProperty(linkRef, ContentModel.PROP_NAME));
                                    text.append(" (");
                                    text.append(nodeService.getProperty(linkRef, ContentModel.PROP_TITLE));
                                    text.append(") ");
                                } catch (Exception e) {
                                    text.append(nodeService.getProperty(child, ContentModel.PROP_NAME));
                                    text.append(" (");
                                    text.append(nodeService.getProperty(child, ContentModel.PROP_TITLE));
                                    text.append(") ");

                                }
                            }
                        } else {
                            System.err.println("TODO: handle " + type + " for " + child);
                        }
                    }

                    String v = text.toString();
                    c.setCellValue(v);
                    if (lines > 1) {
                        c.setCellStyle(styleNewLines);
                        r.setHeightInPoints(lines * sheet.getDefaultRowHeightInPoints());
                    }
                } else if (childAssocs.size() > 0) {
                    StringBuffer text = new StringBuffer();
                    for (ChildAssociationRef childAssociationRef : childAssocs) {
                        NodeRef child = childAssociationRef.getChildRef();
                        QName type = nodeService.getType(child);
                        if (type.equals(ForumModel.TYPE_FORUM)) {
                            List<ChildAssociationRef> topics = nodeService.getChildAssocs(child);
                            if (topics.size() > 0) {
                                ChildAssociationRef topicRef = topics.get(0);
                                List<ChildAssociationRef> comments = nodeService
                                        .getChildAssocs(topicRef.getChildRef());
                                for (ChildAssociationRef commentChildRef : comments) {
                                    NodeRef commentRef = commentChildRef.getChildRef();

                                    ContentData data = (ContentData) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CONTENT);
                                    TemplateContentData contentData = new TemplateContentData(data,
                                            ContentModel.PROP_CONTENT);

                                    String commentString = "";
                                    try {
                                        commentString = contentData.getContentAsText(commentRef, -1);
                                    } catch (Exception e) {
                                        logger.warn("failed to extract content for nodeRef " + commentRef, e);
                                    }

                                    String creator = (String) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CREATOR);
                                    NodeRef person = personService.getPerson(creator, false);
                                    if (person != null) {
                                        creator = nodeService.getProperty(person, ContentModel.PROP_FIRSTNAME)
                                                + " "
                                                + nodeService.getProperty(person, ContentModel.PROP_LASTNAME);
                                    }
                                    Date created = (Date) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CREATED);

                                    text.append(creator).append(" (")
                                            .append(DateFormatUtils.format(created, "yyyy-MM-dd"))
                                            .append("):\n ");
                                    text.append(commentString).append("\n");
                                }
                            }
                        }
                    }
                    String v = text.toString();
                    c.setCellValue(v);
                    c.setCellStyle(styleNewLines);

                } else {
                    // This property isn't set
                    c.setCellType(Cell.CELL_TYPE_BLANK);
                }
            } else {
                // Regular property, set
                if (val instanceof String) {
                    c.setCellValue((String) val);
                    c.setCellStyle(styleNewLines);
                } else if (val instanceof Date) {
                    c.setCellValue((Date) val);
                    c.setCellStyle(styleDate);
                } else if (val instanceof Integer || val instanceof Long) {
                    double v = 0.0;
                    if (val instanceof Long)
                        v = (double) (Long) val;
                    if (val instanceof Integer)
                        v = (double) (Integer) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleInt);
                } else if (val instanceof Float || val instanceof Double) {
                    double v = 0.0;
                    if (val instanceof Float)
                        v = (double) (Float) val;
                    if (val instanceof Double)
                        v = (double) (Double) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleDouble);
                } else {
                    // TODO
                    System.err.println("TODO: handle " + val.getClass().getName() + " - " + val);
                }
            }

            colNum++;
        }

        rowNum++;
    }

    // Sensible column widths please!
    colNum = 0;
    for (QName prop : properties) {
        try {
            sheet.autoSizeColumn(colNum);
        } catch (IllegalArgumentException e) {
            sheet.setColumnWidth(colNum, 40 * 256);
        }

        colNum++;
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.exporter.ExportWorkbook.java

License:Open Source License

/**
 * initializes all styles used in the workbook
 *//*from  w  ww  .j  av a2  s. c  o  m*/
private void initStyles() {

    titleStyle = getWb().createCellStyle();
    headerStyle = getWb().createCellStyle();
    headerTableStyle = getWb().createCellStyle();
    dateStyle = getWb().createCellStyle();
    wrappedStyle = getWb().createCellStyle();
    defaultStyle = getWb().createCellStyle();
    hyperlinkStyle = getWb().createCellStyle();

    DataFormat df = getWb().createDataFormat();

    Font font = getWb().createFont();
    font.setFontHeightInPoints((short) 12);
    font.setFontName(ExcelWorkbook.EXCEL_DEFAULT_FONT);
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    titleStyle.setFont(font);

    font = getWb().createFont();
    font.setFontHeightInPoints((short) 11);
    font.setFontName(ExcelWorkbook.EXCEL_DEFAULT_FONT);
    headerStyle.setFont(font);

    font = getWb().createFont();
    font.setFontHeightInPoints((short) 11);
    font.setFontName(ExcelWorkbook.EXCEL_DEFAULT_FONT);
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    headerTableStyle.setFont(font);

    dateStyle.setDataFormat(df.getFormat("m/d/yy"));
    setAlignementTopLeft(dateStyle);

    wrappedStyle.setWrapText(true);
    setAlignementTopLeft(wrappedStyle);

    setAlignementTopLeft(defaultStyle);

    Font hlinkFont = getWb().createFont();
    hlinkFont.setUnderline(Font.U_SINGLE);
    hlinkFont.setColor(IndexedColors.BLUE.getIndex());
    setAlignementTopLeft(hyperlinkStyle);
    hyperlinkStyle.setFont(hlinkFont);
}