Example usage for org.apache.poi.ss.usermodel CellStyle setDataFormat

List of usage examples for org.apache.poi.ss.usermodel CellStyle setDataFormat

Introduction

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

Prototype

void setDataFormat(short fmt);

Source Link

Document

set the data format (must be a valid format).

Usage

From source file:om.edu.squ.squportal.portlet.tsurvey.dao.excel.TeachingSurveyExcelImpl.java

License:Open Source License

/**
 * //from w w w .  j  ava 2  s. co m
 * method name  : createStyles
 * @param wb
 * @return
 * TeachingSurveyExcelImpl
 * return type  : Map<String,CellStyle>
 * 
 * purpose      :   Creating Styles for Excell sheet cells
 *
 * Date          :   Mar 16, 2016 1:25:00 PM
 */
private static Map<String, CellStyle> createStyles(Workbook wb) {
    Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
    CellStyle style;

    /*** TITLE  ***/
    Font titleFont = wb.createFont();
    titleFont.setFontHeightInPoints((short) 18);
    titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    style.setFont(titleFont);
    styles.put(TITLE, style);

    /*** SUB-HEADER  ***/
    Font subHeaderFont = wb.createFont();
    subHeaderFont.setFontHeightInPoints((short) 9);
    subHeaderFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    style = wb.createCellStyle();
    style.setFont(subHeaderFont);
    style.setWrapText(true);
    styles.put(SUB_HEADER, style);

    /*** MAX. TWO DIGIT DECIMAL VALUE  ***/
    style = wb.createCellStyle();
    style.setDataFormat(wb.createDataFormat().getFormat("0.00"));
    styles.put(FORMULA_1, style);

    return styles;
}

From source file:onl.netfishers.netshot.RestService.java

License:Open Source License

@GET
@Path("reports/export")
@RolesAllowed("readonly")
@Produces({ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" })
public Response getDataXLSX(@Context HttpServletRequest request,
        @DefaultValue("-1") @QueryParam("group") long group,
        @DefaultValue("false") @QueryParam("interfaces") boolean exportInterfaces,
        @DefaultValue("false") @QueryParam("inventory") boolean exportInventory,
        @DefaultValue("xlsx") @QueryParam("format") String fileFormat) throws WebApplicationException {
    logger.debug("REST request, export data.");
    User user = (User) request.getSession().getAttribute("user");

    if (fileFormat.compareToIgnoreCase("xlsx") == 0) {
        String fileName = String.format("netshot-export_%s.xlsx",
                (new SimpleDateFormat("yyyyMMdd-HHmmss")).format(new Date()));

        Session session = Database.getSession();
        try {/*from w w  w  .ja v  a 2  s  .c o m*/
            Workbook workBook = new XSSFWorkbook();
            Row row;
            Cell cell;

            CreationHelper createHelper = workBook.getCreationHelper();
            CellStyle datetimeCellStyle = workBook.createCellStyle();
            datetimeCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd hh:mm"));
            CellStyle dateCellStyle = workBook.createCellStyle();
            dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));

            Sheet summarySheet = workBook.createSheet("Summary");
            row = summarySheet.createRow(0);
            row.createCell(0).setCellValue("Netshot version");
            row.createCell(1).setCellValue(Netshot.VERSION);
            row = summarySheet.createRow(1);
            row.createCell(0).setCellValue("Exported by");
            row.createCell(1).setCellValue(user.getName());
            row = summarySheet.createRow(2);
            row.createCell(0).setCellValue("Date and time");
            cell = row.createCell(1);
            cell.setCellValue(new Date());
            cell.setCellStyle(datetimeCellStyle);
            row = summarySheet.createRow(4);
            row.createCell(0).setCellValue("Selected Group");
            Query query;
            if (group == -1) {
                query = session.createQuery("select d from Device d");
                row.createCell(1).setCellValue("None");
            } else {
                query = session.createQuery("select d from Device d join d.ownerGroups g where g.id = :id")
                        .setLong("id", group);
                DeviceGroup deviceGroup = (DeviceGroup) session.get(DeviceGroup.class, group);
                row.createCell(1).setCellValue(deviceGroup.getName());
            }

            Sheet deviceSheet = workBook.createSheet("Devices");
            row = deviceSheet.createRow(0);
            row.createCell(0).setCellValue("ID");
            row.createCell(1).setCellValue("Name");
            row.createCell(2).setCellValue("Management IP");
            row.createCell(3).setCellValue("Domain");
            row.createCell(4).setCellValue("Network Class");
            row.createCell(5).setCellValue("Family");
            row.createCell(6).setCellValue("Creation");
            row.createCell(7).setCellValue("Last Change");
            row.createCell(8).setCellValue("Software");
            row.createCell(9).setCellValue("End of Sale Date");
            row.createCell(10).setCellValue("End Of Life Date");

            int yDevice = 1;

            @SuppressWarnings("unchecked")
            List<Device> devices = query.list();
            for (Device device : devices) {
                row = deviceSheet.createRow(yDevice++);
                row.createCell(0).setCellValue(device.getId());
                row.createCell(1).setCellValue(device.getName());
                row.createCell(2).setCellValue(device.getMgmtAddress().getIp());
                row.createCell(3).setCellValue(device.getMgmtDomain().getName());
                row.createCell(4).setCellValue(device.getNetworkClass().toString());
                row.createCell(5).setCellValue(device.getFamily());
                cell = row.createCell(6);
                cell.setCellValue(device.getCreatedDate());
                cell.setCellStyle(datetimeCellStyle);
                cell = row.createCell(7);
                cell.setCellValue(device.getChangeDate());
                cell.setCellStyle(datetimeCellStyle);
                row.createCell(8).setCellValue(device.getSoftwareVersion());
                if (device.getEosDate() != null) {
                    cell = row.createCell(9);
                    cell.setCellValue(device.getEosDate());
                    cell.setCellStyle(dateCellStyle);
                }
                if (device.getEolDate() != null) {
                    cell = row.createCell(10);
                    cell.setCellValue(device.getEolDate());
                    cell.setCellStyle(dateCellStyle);
                }
            }

            if (exportInterfaces) {
                Sheet interfaceSheet = workBook.createSheet("Interfaces");
                row = interfaceSheet.createRow(0);
                row.createCell(0).setCellValue("Device ID");
                row.createCell(1).setCellValue("Virtual Device");
                row.createCell(2).setCellValue("Name");
                row.createCell(3).setCellValue("Description");
                row.createCell(4).setCellValue("VRF");
                row.createCell(5).setCellValue("MAC Address");
                row.createCell(6).setCellValue("Enabled");
                row.createCell(7).setCellValue("Level 3");
                row.createCell(8).setCellValue("IP Address");
                row.createCell(9).setCellValue("Mask Length");
                row.createCell(10).setCellValue("Usage");

                int yInterface = 1;
                for (Device device : devices) {
                    for (NetworkInterface networkInterface : device.getNetworkInterfaces()) {
                        if (networkInterface.getIpAddresses().size() == 0) {
                            row = interfaceSheet.createRow(yInterface++);
                            row.createCell(0).setCellValue(device.getId());
                            row.createCell(1).setCellValue(networkInterface.getVirtualDevice());
                            row.createCell(2).setCellValue(networkInterface.getInterfaceName());
                            row.createCell(3).setCellValue(networkInterface.getDescription());
                            row.createCell(4).setCellValue(networkInterface.getVrfInstance());
                            row.createCell(5).setCellValue(networkInterface.getMacAddress());
                            row.createCell(6).setCellValue(networkInterface.isEnabled());
                            row.createCell(7).setCellValue(networkInterface.isLevel3());
                            row.createCell(8).setCellValue("");
                            row.createCell(9).setCellValue("");
                            row.createCell(10).setCellValue("");
                        }
                        for (NetworkAddress address : networkInterface.getIpAddresses()) {
                            row = interfaceSheet.createRow(yInterface++);
                            row.createCell(0).setCellValue(device.getId());
                            row.createCell(1).setCellValue(networkInterface.getVirtualDevice());
                            row.createCell(2).setCellValue(networkInterface.getInterfaceName());
                            row.createCell(3).setCellValue(networkInterface.getDescription());
                            row.createCell(4).setCellValue(networkInterface.getVrfInstance());
                            row.createCell(5).setCellValue(networkInterface.getMacAddress());
                            row.createCell(6).setCellValue(networkInterface.isEnabled());
                            row.createCell(7).setCellValue(networkInterface.isLevel3());
                            row.createCell(8).setCellValue(address.getIp());
                            row.createCell(9).setCellValue(address.getPrefixLength());
                            row.createCell(10).setCellValue(address.getAddressUsage() == null ? ""
                                    : address.getAddressUsage().toString());
                        }
                    }
                }
            }

            if (exportInventory) {
                Sheet inventorySheet = workBook.createSheet("Inventory");
                row = inventorySheet.createRow(0);
                row.createCell(0).setCellValue("Device ID");
                row.createCell(1).setCellValue("Slot");
                row.createCell(2).setCellValue("Part Number");
                row.createCell(3).setCellValue("Serial Number");

                int yInventory = 1;
                for (Device device : devices) {
                    for (Module module : device.getModules()) {
                        row = inventorySheet.createRow(yInventory++);
                        row.createCell(0).setCellValue(device.getId());
                        row.createCell(1).setCellValue(module.getSlot());
                        row.createCell(2).setCellValue(module.getPartNumber());
                        row.createCell(3).setCellValue(module.getSerialNumber());
                    }
                }
            }

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            workBook.write(output);
            workBook.close();
            return Response.ok(output.toByteArray())
                    .header("Content-Disposition", "attachment; filename=" + fileName).build();
        } catch (IOException e) {
            logger.error("Unable to write the resulting file.", e);
            throw new WebApplicationException("Unable to write the resulting file.",
                    javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            logger.error("Unable to generate the report.", e);
            throw new WebApplicationException("Unable to generate the report.",
                    javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR);
        } finally {
            session.close();
        }
    }

    logger.warn("Invalid requested file format.");
    throw new WebApplicationException("The requested file format is invalid or not supported.",
            javax.ws.rs.core.Response.Status.BAD_REQUEST);

}

From source file:opn.greenwebs.FXMLDocumentController.java

private void inject(XSSFWorkbook wb, Object obj, int row, int col) {
    if (wb == null) {
        System.out.println("wb is null");
    }/*from w ww  .  j a v a 2s  .  com*/
    XSSFSheet sheet = wb.getSheet("Digital Version");
    Row rowed = sheet.getRow(row);
    Cell cell = rowed.getCell(col);
    CellStyle cellStyle = cell.getCellStyle();
    XSSFFont font = sheet.getWorkbook().createFont();
    font.setFontHeight(14);
    cellStyle.setFont(font);
    if (obj instanceof String) {
        cell.setCellValue((String) obj);
    } else if (obj instanceof Boolean) {
        cell.setCellValue((Boolean) obj);
    } else if (obj instanceof Date) {
        CreationHelper createHelper = wb.getCreationHelper();
        cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("mm/dd/yyyy"));
        cell.setCellValue((Date) obj);
    } else if (obj instanceof Double) {
        cell.setCellValue((Double) obj);
    } else if (obj instanceof Integer) {
        cell.setCellValue((int) obj);
    }
    cell.setCellStyle(cellStyle);
}

From source file:opn.greenwebs.FXMLDocumentController.java

private void injectStock(XSSFWorkbook wbs, Object obj, int row, int col) {

    Row rowed = wbs.getSheet("Digital Version").getRow(row);
    Cell cell = rowed.getCell(col);//from  ww w  .ja  va2s . c o m
    if (obj instanceof String) {
        cell.setCellValue((String) obj);
    } else if (obj instanceof Boolean) {
        cell.setCellValue((Boolean) obj);
    } else if (obj instanceof Date) {
        CellStyle cellStyle = wbs.getCellStyleAt(col);
        CreationHelper createHelper = wbs.getCreationHelper();
        cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("mm/dd/yyyy"));
        cell.setCellValue((Date) obj);
        cell.setCellStyle(cellStyle);
    } else if (obj instanceof Double) {
        cell.setCellValue((Double) obj);
    } else if (obj instanceof Integer) {
        cell.setCellValue((int) obj);
    }
}

From source file:org.aio.handy.poi.ConditionalFormats.java

License:Apache License

/**
 * Use Excel conditional formatting to highlight payments that are due in
 * the next thirty days. In this example, Due dates are entered in cells
 * A2:A4./*w ww . j  av  a 2s .co m*/
 */
static void expiry(Sheet sheet) {
    CellStyle style = sheet.getWorkbook().createCellStyle();
    style.setDataFormat((short) BuiltinFormats.getBuiltinFormat("d-mmm"));

    sheet.createRow(0).createCell(0).setCellValue("Date");
    sheet.createRow(1).createCell(0).setCellFormula("TODAY()+29");
    sheet.createRow(2).createCell(0).setCellFormula("A2+1");
    sheet.createRow(3).createCell(0).setCellFormula("A3+1");

    for (int rownum = 1; rownum <= 3; rownum++)
        sheet.getRow(rownum).getCell(0).setCellStyle(style);

    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

    // Condition 1: Formula Is =A2=A1 (White Font)
    ConditionalFormattingRule rule1 = sheetCF
            .createConditionalFormattingRule("AND(A2-TODAY()>=0,A2-TODAY()<=30)");
    FontFormatting font = rule1.createFontFormatting();
    font.setFontStyle(false, true);
    font.setFontColorIndex(IndexedColors.BLUE.index);

    CellRangeAddress[] regions = { CellRangeAddress.valueOf("A2:A4") };

    sheetCF.addConditionalFormatting(regions, rule1);

    sheet.getRow(0).createCell(1).setCellValue("Dates within the next 30 days are highlighted");
}

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

License:Open Source License

public static CellStyle createCellStyle(Workbook workbook, cfStructData _struct) throws Exception {
    CellStyle style = workbook.createCellStyle();

    if (_struct.containsKey("alignment")) {
        String v = _struct.getData("alignment").getString();
        Short s = lookup_alignment.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'alignment' (" + v + ")");
        } else//from  ww  w  .ja va 2  s  .c  om
            style.setAlignment(s);
    }

    if (_struct.containsKey("bottomborder")) {
        String v = _struct.getData("bottomborder").getString();
        Short s = lookup_border.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'bottomborder' (" + v + ")");
        } else
            style.setBorderBottom(s);
    }

    if (_struct.containsKey("topborder")) {
        String v = _struct.getData("topborder").getString();
        Short s = lookup_border.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'topborder' (" + v + ")");
        } else
            style.setBorderTop(s);
    }

    if (_struct.containsKey("leftborder")) {
        String v = _struct.getData("leftborder").getString();
        Short s = lookup_border.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'leftborder' (" + v + ")");
        } else
            style.setBorderLeft(s);
    }

    if (_struct.containsKey("rightborder")) {
        String v = _struct.getData("rightborder").getString();
        Short s = lookup_border.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'rightborder' (" + v + ")");
        } else
            style.setBorderRight(s);
    }

    if (_struct.containsKey("bottombordercolor")) {
        String v = _struct.getData("bottombordercolor").getString();
        Short s = lookup_colors.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'bottombordercolor' (" + v + ")");
        } else
            style.setBottomBorderColor(s);
    }

    if (_struct.containsKey("topbordercolor")) {
        String v = _struct.getData("topbordercolor").getString();
        Short s = lookup_colors.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'topbordercolor' (" + v + ")");
        } else
            style.setTopBorderColor(s);
    }

    if (_struct.containsKey("leftbordercolor")) {
        String v = _struct.getData("leftbordercolor").getString();
        Short s = lookup_colors.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'leftbordercolor' (" + v + ")");
        } else
            style.setLeftBorderColor(s);
    }

    if (_struct.containsKey("rightbordercolor")) {
        String v = _struct.getData("rightbordercolor").getString();
        Short s = lookup_colors.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'rightbordercolor' (" + v + ")");
        } else
            style.setRightBorderColor(s);
    }

    if (_struct.containsKey("fillpattern")) {
        String v = _struct.getData("fillpattern").getString();
        Short s = lookup_fillpatten.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'fillpattern' (" + v + ")");
        } else
            style.setFillPattern(s);
    }

    if (_struct.containsKey("fgcolor")) {
        String v = _struct.getData("fgcolor").getString();
        Short s = lookup_colors.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'fgcolor' (" + v + ")");
        } else
            style.setFillForegroundColor(s);
    }

    if (_struct.containsKey("bgcolor")) {
        String v = _struct.getData("bgcolor").getString();
        Short s = lookup_colors.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'bgcolor' (" + v + ")");
        } else
            style.setFillBackgroundColor(s);
    }

    if (_struct.containsKey("textwrap")) {
        Boolean b = _struct.getData("textwrap").getBoolean();
        style.setWrapText(b);
    }

    if (_struct.containsKey("hidden")) {
        Boolean b = _struct.getData("hidden").getBoolean();
        style.setHidden(b);
    }

    if (_struct.containsKey("locked")) {
        Boolean b = _struct.getData("locked").getBoolean();
        style.setLocked(b);
    }

    if (_struct.containsKey("indent")) {
        style.setIndention((short) _struct.getData("indent").getInt());
    }

    if (_struct.containsKey("rotation")) {
        style.setRotation((short) _struct.getData("rotation").getInt());
    }

    if (_struct.containsKey("dateformat")) {
        style.setDataFormat(workbook.createDataFormat().getFormat(_struct.getData("dateformat").getString()));
    }

    // Manage the fonts
    Font f = workbook.createFont();

    if (_struct.containsKey("strikeout")) {
        f.setStrikeout(true);
    }

    if (_struct.containsKey("bold")) {
        Boolean b = _struct.getData("bold").getBoolean();
        f.setBoldweight(b ? Font.BOLDWEIGHT_BOLD : Font.BOLDWEIGHT_NORMAL);
    }

    if (_struct.containsKey("underline")) {
        String v = _struct.getData("underline").getString();
        Byte b = lookup_underline.get(v);
        if (b == null) {
            throw new Exception("invalid parameter for 'underline' (" + v + ")");
        } else
            f.setUnderline(b);
    }

    if (_struct.containsKey("color")) {
        String v = _struct.getData("color").getString();
        Short s = lookup_colors.get(v);
        if (s == null) {
            throw new Exception("invalid parameter for 'color' (" + v + ")");
        } else
            f.setColor(s);
    }

    if (_struct.containsKey("fontsize")) {
        int s = _struct.getData("fontsize").getInt();
        f.setFontHeightInPoints((short) s);
    }

    if (_struct.containsKey("font")) {
        f.setFontName(_struct.getData("font").getString());
    }

    style.setFont(f);

    return style;
}

From source file:org.alfresco.repo.web.scripts.datalist.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;/*from  w w w  .  j a  v  a  2 s  .  c o  m*/
    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);

            Serializable val = nodeService.getProperty(item, prop);
            if (val == null) {
                // Is it an association, or just missing?
                List<AssociationRef> assocs = nodeService.getTargetAssocs(item, prop);
                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_USERNAME));
                        } 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_TITLE));
                        } 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 {
                    // This property isn't set
                    c.setCellType(Cell.CELL_TYPE_BLANK);
                }
            } else {
                // Regular property, set
                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 " + val.getClass().getName() + " - " + val);
                }
            }

            colNum++;
        }

        rowNum++;
    }

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

From source file:org.centralperf.helper.view.ExcelOOXMLView.java

License:Open Source License

/**
 * @see AbstractPOIExcelView#buildExcelDocument(Map, Workbook, HttpServletRequest, HttpServletResponse)
 *//*from   w  ww .ja v a  2 s .  c om*/
@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    log.debug("Generating Excel report from run samples");

    // Set the headers
    response.setHeader("Content-Type", "application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=central_perf_result.xlsx");

    // get data model which is passed by the Spring container
    Run run = (Run) model.get("run");

    // Set run summary informations
    setCellValueByName(PROJECT_NAME_CELL_NAME, run.getProject().getName(), workbook);
    setCellValueByName(RUN_LABEL_CELL_NAME, run.getLabel(), workbook);
    setCellValueByName(RUN_DESCRIPTION_CELL_NAME, run.getComment(), workbook);
    setCellValueByName(START_DATE_CELL_NAME, run.getStartDate().toString(), workbook);
    setCellValueByName(START_DATE_CELL_NAME, run.getStartDate().toString(), workbook);
    setCellValueByName(GENERATED_ON_CELL_NAME, "" + unixTimestamp2ExcelTimestampconvert(new Date().getTime()),
            workbook);

    // Populate data sheet
    XSSFSheet dataSheet = (XSSFSheet) workbook.getSheet(DATA_SHEET_NAME);
    // Set date style for first column
    CellStyle dateStyle = workbook.createCellStyle();
    CreationHelper createHelper = workbook.getCreationHelper();
    dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/mm/dd"));
    dataSheet.setDefaultColumnStyle(0, dateStyle);

    // Add samples
    for (int i = 0; i < run.getSamples().size(); i++) {
        Sample sample = run.getSamples().get(i);
        XSSFRow dataRow = dataSheet.createRow(i + 1);
        if (sample.getTimestamp() != null) {
            dataRow.createCell(0)
                    .setCellValue(unixTimestamp2ExcelTimestampconvert(sample.getTimestamp().getTime()));
            dataRow.createCell(1).setCellValue(sample.getElapsed());
            dataRow.createCell(2).setCellValue(sample.getSampleName());
            dataRow.createCell(3).setCellValue(sample.getStatus());
            dataRow.createCell(4).setCellValue(sample.getReturnCode());
            dataRow.createCell(5).setCellValue(sample.getSizeInOctet());
            dataRow.createCell(6).setCellValue(sample.getGrpThreads());
            dataRow.createCell(7).setCellValue(sample.getAllThreads());
            dataRow.createCell(8).setCellValue(sample.getLatency());
        }
    }

    // Return generated sheet
    OutputStream outStream = null;
    try {
        outStream = response.getOutputStream();
        workbook.write(outStream);
        outStream.flush();
    } finally {
        outStream.close();
    }

}

From source file:org.codelabor.example.poi.xssf.usermodel.XSSFWorkbookTest.java

License:Apache License

@Test
public void testSetCellStyle() {
    String path = "C:/temp/workbook4.xlsx";
    OutputStream outputStream = null;
    try {/*w ww.  j  a v  a  2 s  . c o m*/
        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet sheet1 = workbook.createSheet("Sheet1");
        CreationHelper creationHelper = workbook.getCreationHelper();
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-mm-dd hh:mm"));

        Row row = sheet1.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue(new Date());

        cell = row.createCell(1);
        cell.setCellValue(new Date());
        cell.setCellStyle(cellStyle);

        cell = row.createCell(2);
        cell.setCellValue(Calendar.getInstance());
        cell.setCellStyle(cellStyle);

        outputStream = new FileOutputStream(path);
        workbook.write(outputStream);
    } catch (IOException e) {
        e.printStackTrace();
        fail();
    } finally {
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.dashbuilder.dataset.backend.DataSetBackendServicesImpl.java

License:Apache License

private Map<String, CellStyle> createStyles(Workbook wb) {
    Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
    CellStyle style;

    Font titleFont = wb.createFont();
    titleFont.setFontHeightInPoints((short) 12);
    titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style = wb.createCellStyle();/*w  w w.  ja va  2s  .  c  o  m*/
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setFont(titleFont);
    style.setWrapText(false);
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBottomBorderColor(IndexedColors.GREY_80_PERCENT.getIndex());
    styles.put("header", style);

    Font cellFont = wb.createFont();
    cellFont.setFontHeightInPoints((short) 10);
    cellFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);

    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM);
    style.setFont(cellFont);
    style.setWrapText(false);
    style.setDataFormat(wb.createDataFormat().getFormat(BuiltinFormats.getBuiltinFormat(3)));
    styles.put("integer_number_cell", style);

    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM);
    style.setFont(cellFont);
    style.setWrapText(false);
    style.setDataFormat(wb.createDataFormat().getFormat(BuiltinFormats.getBuiltinFormat(4)));
    styles.put("decimal_number_cell", style);

    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM);
    style.setFont(cellFont);
    style.setWrapText(false);
    style.setDataFormat((short) BuiltinFormats.getBuiltinFormat("text"));
    styles.put("text_cell", style);

    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM);
    style.setFont(cellFont);
    style.setWrapText(false);
    style.setDataFormat(wb.createDataFormat()
            .getFormat(DateFormatConverter.convert(Locale.getDefault(), dateFormatPattern)));
    styles.put("date_cell", style);
    return styles;
}