Example usage for org.apache.poi.hssf.usermodel HSSFCellStyle setAlignment

List of usage examples for org.apache.poi.hssf.usermodel HSSFCellStyle setAlignment

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFCellStyle setAlignment.

Prototype

@Override
public void setAlignment(HorizontalAlignment align) 

Source Link

Document

set the type of horizontal alignment for the cell

Usage

From source file:net.vpc.app.vainruling.core.web.jsf.Vr.java

public void postProcessDataExporterXLS(Object document) {
    HSSFWorkbook book = (HSSFWorkbook) document;
    HSSFSheet sheet = book.getSheetAt(0);
    HSSFRow header = sheet.getRow(0);//from   w ww . j  a va  2 s  .c  om
    int rowCount = sheet.getPhysicalNumberOfRows();
    HSSFCellStyle headerCellStyle = book.createCellStyle();
    headerCellStyle.setFillForegroundColor(HSSFColor.AQUA.index);
    headerCellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    headerCellStyle.setAlignment(CellStyle.ALIGN_CENTER);
    HSSFCreationHelper creationHelper = book.getCreationHelper();

    for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
        HSSFCell cell = header.getCell(i);

        cell.setCellStyle(headerCellStyle);
    }

    HSSFCellStyle intStyle = book.createCellStyle();
    intStyle.setDataFormat((short) 1);

    HSSFCellStyle decStyle = book.createCellStyle();
    decStyle.setDataFormat((short) 2);

    HSSFCellStyle dollarStyle = book.createCellStyle();
    dollarStyle.setDataFormat((short) 5);

    int maxColumn = -1;
    Map<String, HSSFCellStyle> datFormats = new HashMap<>();
    for (int rowInd = 1; rowInd < rowCount; rowInd++) {
        HSSFRow row = sheet.getRow(rowInd);
        int colCount = row.getPhysicalNumberOfCells();
        if (maxColumn < colCount) {
            maxColumn = colCount;
        }
        for (int cellInd = 0; cellInd < colCount; cellInd++) {
            HSSFCell cell = row.getCell(cellInd);

            String strVal = cell.getStringCellValue();

            if (strVal.startsWith("$")) {
                //do nothing
            } else {
                if (strVal.startsWith("'")) {
                    strVal = strVal.substring(1);
                }
                if (PlatformUtils.isDouble(strVal)) {
                    cell.setCellType(HSSFCell.CELL_TYPE_BLANK);
                    cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                    if (PlatformUtils.isInteger(strVal)) {
                        int intVal = Integer.valueOf(strVal.trim());
                        cell.setCellStyle(intStyle);
                        cell.setCellValue(intVal);
                    } else if (PlatformUtils.isDouble(strVal)) {
                        double dblVal = Double.valueOf(strVal.trim());
                        cell.setCellStyle(decStyle);
                        cell.setCellValue(dblVal);
                    }
                } else {
                    boolean isDate = false;
                    for (String dteFormat : new String[] { "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss",
                            "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "HH:mm" }) {
                        if (PlatformUtils.isDate(strVal, dteFormat)) {
                            HSSFCellStyle dateStyle = datFormats.get(dteFormat.trim());
                            if (dateStyle == null) {
                                dateStyle = book.createCellStyle();
                                dateStyle.setDataFormat(creationHelper.createDataFormat().getFormat(dteFormat));
                                datFormats.put(dteFormat, dateStyle);
                            }
                            cell.setCellStyle(dateStyle);
                            try {
                                cell.setCellValue(new SimpleDateFormat(dteFormat).parse(strVal));
                            } catch (ParseException e) {
                                //
                            }
                            isDate = true;
                            break;
                        }
                    }

                }
            }
        }
    }
    if (maxColumn >= 0) {
        for (int cellInd = 0; cellInd < maxColumn; cellInd++) {
            sheet.autoSizeColumn(cellInd);
        }
    }

}

From source file:org.anyframe.logmanager.web.LogManagerController.java

License:Apache License

/**
 * log data export for excel file type/*from   ww w .j  a v a  2  s .  c  o m*/
 * 
 * @param searchCondition
 * @param model
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping(params = "method=xlsExport")
public void xlsExport(LogSearchCondition searchCondition, Model model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    searchCondition.setPageIndex(-1);
    searchCondition.setCollection(searchCondition.getRepositoryName());

    String fileName = null;
    String sDate = null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", new Locale("ko_KR"));
    sDate = sdf.format(new Date());
    StringBuffer sb = new StringBuffer();
    sb.append(searchCondition.getAppName().substring(searchCondition.getAppName().lastIndexOf("/") + 1));
    sb.append("_").append(searchCondition.getCollection()).append("_").append(sDate).append(".xls");
    fileName = sb.toString();

    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-ddHHmm");
    logger.debug("from:{}",
            searchCondition.getFromDate() + searchCondition.getFromHour() + searchCondition.getFromMinute());
    logger.debug("to:{}",
            searchCondition.getToDate() + searchCondition.getToHour() + searchCondition.getToMinute());
    if (searchCondition.isUseFromDate())
        searchCondition.setFromDateTime(dateTimeFormat.parse(searchCondition.getFromDate()
                + searchCondition.getFromHour() + searchCondition.getFromMinute()));
    if (searchCondition.isUseToDate())
        searchCondition.setToDateTime(dateTimeFormat.parse(
                searchCondition.getToDate() + searchCondition.getToHour() + searchCondition.getToMinute()));

    List<LogDataMap> resultList = service.searchAnalysisLog(searchCondition);

    response.reset();
    response.setContentType("application/x-msexcel;charset=MS949");
    // response.setContentType("application/octet-stream");
    String userAgent = request.getHeader("User-Agent");

    if (userAgent.indexOf("MSIE 5.5") > -1) {
        response.setHeader("Content-Disposition", "filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\";");
    } else if (userAgent.indexOf("MSIE") > -1) {
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + java.net.URLEncoder.encode(fileName, "UTF-8") + "\";");
    } else {
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + new String(fileName.getBytes("euc-kr"), "latin1") + "\";");
    }
    response.setHeader("Content-Description", "JSP Generated Data");
    response.setHeader("Content-Transfer-Encoding", "binary;");
    response.setHeader("Pragma", "no-cache;");
    response.setHeader("Expires", "-1;");

    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet(fileName);

    OutputStream fileOut = null;
    try {
        fileOut = response.getOutputStream();
        HSSFRow row = null;
        HSSFRow headerRow = null;

        HSSFDataFormat df = workbook.createDataFormat();

        HSSFCellStyle headerStyle = workbook.createCellStyle();
        HSSFFont boldFont = workbook.createFont();
        boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headerStyle.setFont(boldFont);
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle dateStyle = workbook.createCellStyle();
        dateStyle.setDataFormat(df.getFormat("yyyy-mm-dd h:mm:ss.000"));
        dateStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        dateStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCellStyle messageStyle = workbook.createCellStyle();
        messageStyle.setWrapText(true);
        messageStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        messageStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFCell cell;
        HSSFCell headerCell;

        short width = 265;

        Iterator<String> j = null;
        String key = null;
        int cellIndex = 0;
        int listSize = 0;

        String level = null;
        Date timestamp = null;
        String message = null;

        if (resultList != null) {
            listSize = resultList.size();
            for (int i = 0; i < listSize; i++) {
                LogDataMap log = (LogDataMap) resultList.get(i);
                if (i == 0) {
                    headerRow = sheet.createRow(i); // level header
                    sheet.setColumnWidth(0, 7 * width);
                    headerCell = headerRow.createCell(0);
                    HSSFRichTextString headerValue = new HSSFRichTextString("level");
                    headerCell.setCellValue(headerValue);
                    headerCell.setCellStyle(headerStyle);

                    headerCell = headerRow.createCell(1); // time stamp header
                    sheet.setColumnWidth(1, 24 * width);
                    headerValue = new HSSFRichTextString("timestamp");
                    headerCell.setCellValue(headerValue);
                    headerCell.setCellStyle(headerStyle);

                    headerCell = headerRow.createCell(2); // message header
                    sheet.setColumnWidth(2, 70 * width);
                    headerValue = new HSSFRichTextString("message");
                    headerCell.setCellValue(headerValue);
                    headerCell.setCellStyle(headerStyle);
                }

                row = sheet.createRow(i + 1);

                // level
                level = (String) log.get("level");
                cell = row.createCell(0);
                cell.setCellStyle(style);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                cell.setCellValue(level);

                // timestamp
                timestamp = (Date) log.get("timestamp");
                cell = row.createCell(1);
                cell.setCellStyle(dateStyle);
                cell.setCellValue(timestamp);

                // message
                message = (String) log.get("message");
                HSSFRichTextString messageValue = new HSSFRichTextString(message);
                cell = row.createCell(2);
                cell.setCellStyle(messageStyle);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                cell.setCellValue(messageValue);

                cellIndex = 3;
                j = log.keySet().iterator();
                while (j.hasNext()) {
                    key = j.next();
                    if ("_id".equals(key) || "message".equals(key) || "timestamp".equals(key)
                            || "level".equals(key)) {
                        continue;
                    }
                    //logger.debug("key=" + key);
                    if (i == 0) {
                        sheet.setColumnWidth(cellIndex, 20 * width);

                        headerCell = headerRow.createCell(cellIndex);
                        HSSFRichTextString headerValue = new HSSFRichTextString(key);
                        headerCell.setCellValue(headerValue);
                        headerCell.setCellStyle(headerStyle);
                    }
                    cell = row.createCell(cellIndex);
                    Object value = log.get(key);
                    if (value instanceof Date) {
                        cell.setCellStyle(dateStyle);
                        cell.setCellValue((Date) value);
                    } else {
                        cell.setCellStyle(style);
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        cell.setCellValue((String) log.get(key));
                    }

                    cellIndex++;
                }
            }
            workbook.write(fileOut);
        }
    } catch (Exception e) {
        throw e;
    } finally {
        try {
            if (fileOut != null) {
                fileOut.flush();
                fileOut.close();
            }
        } catch (IOException ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }
}

From source file:org.apache.cocoon.components.elementprocessor.impl.poi.hssf.elements.EPStyle.java

License:Apache License

/**
 * Override of Initialize() implementation
 * @param attributes the array of Attribute instances; may be empty, will
 *                  never be null//from   ww  w.  j a  va2  s.  c  om
 * @param parent the parent ElementProcessor; may be null
 * @exception IOException if anything is wrong
 */
public void initialize(final Attribute[] attributes, final ElementProcessor parent) throws IOException {
    super.initialize(attributes, parent);

    EPStyleRegion sregion = (EPStyleRegion) parent;

    if (sregion.isValid()) {
        Hashtable colorhash = sregion.getColorHash();

        HSSFCellStyle style = sregion.getStyle();
        short cnvhalign = convertAlignment(getHorizontalAlignment().getCode());
        style.setAlignment(cnvhalign);
        short cnvvalign = convertVAlignment(getVerticalAlignment().getCode());
        style.setVerticalAlignment(cnvvalign);
        style.setFillPattern((short) getShade());

        Workbook workbook = getWorkbook();
        HSSFDataFormat dataformat = workbook.createDataFormat();
        if (getShade() == 1) {
            // TODO: change to constant when upgrade to new HSSF
            // solid w/foreground, bg doesn't matter
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("shade = 1");
            }
            HSSFColor color = (HSSFColor) colorhash.get(getBackgroundColor().toString());
            if (color == null) {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("s1 BG couldn't find color for " + getBackgroundColor().toString());
                }
                color = new HSSFColor.WHITE();
            }
            style.setFillForegroundColor(color.getIndex());
            color = (HSSFColor) colorhash.get(getPatternColor().toString());
            if (color == null) {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("s1 PC couldn't find color for " + getPatternColor().toString());
                }
                color = new HSSFColor.BLACK();
            }
            style.setFillBackgroundColor(color.getIndex());
        } else {
            HSSFColor color = (HSSFColor) colorhash.get(getBackgroundColor().toString());
            if (color == null) {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("BG couldn't find color for " + getBackgroundColor().toString());
                }
                color = new HSSFColor.BLACK();
            }
            style.setFillBackgroundColor(color.getIndex());
            color = (HSSFColor) colorhash.get(getPatternColor().toString());
            if (color == null) {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("PC couldn't find color for " + getPatternColor().toString());
                }
                color = new HSSFColor.WHITE();
            }
            style.setFillForegroundColor(color.getIndex());
        }
        style.setWrapText(getWrapText());
        style.setLocked(true);

        String format = null;
        try {
            format = getFormat();
        } catch (NullPointerException e) {
            format = _general_format;
        }

        if (!_general_format.equals(format)) {
            short valuenumber;
            format = kludgeForGnumericMisformats(format);
            format = kludgeForGnumericDateDivergence(format);
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("setting format to " + format);
            }
            Object o = workbook.getValidate(format, dataformat.getFormat(format));
            Short sh = null;
            sh = (Short) o;
            valuenumber = sh.shortValue();
            style.setDataFormat(valuenumber);
        }
    } else {
        invalid = true;
    }
}

From source file:org.beangle.commons.transfer.excel.ExcelItemWriter.java

License:Open Source License

/**
 * <p>/*from   w ww .  ja  v  a 2 s .  co m*/
 * getTitleStyle.
 * </p>
 * 
 * @return a {@link org.apache.poi.hssf.usermodel.HSSFCellStyle} object.
 */
protected HSSFCellStyle getTitleStyle() {
    HSSFCellStyle style = workbook.createCellStyle();
    // HSSFFont f = workbook.createFont();
    // f.setFontHeightInPoints((short ) 10 ); //?
    // f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//
    // style.setFont(f);
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// ?
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 
    style.setFillPattern(HSSFCellStyle.FINE_DOTS);
    style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    style.setFillBackgroundColor(HSSFColor.LIGHT_BLUE.index);
    return style;
}

From source file:org.beangle.model.transfer.excel.ExcelItemWriter.java

License:Open Source License

protected HSSFCellStyle getTitleStyle() {
    HSSFCellStyle style = workbook.createCellStyle();
    HSSFFont f = workbook.createFont();//from   w  w w . j  a va2s .c o  m
    f.setFontHeightInPoints((short) 10); // ?
    //      f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 
    f.setColor(HSSFColor.WHITE.index);
    style.setFont(f);
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// ?
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    style.setFillForegroundColor(HSSFColor.DARK_TEAL.index);
    //      style.setFillBackgroundColor(HSSFColor.LIGHT_BLUE.index);
    return style;
}

From source file:org.deployom.core.AuditService.java

License:Open Source License

public HSSFWorkbook saveAudit() {

    // Create book
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFCreationHelper creationHelper = workbook.getCreationHelper();

    // Default Style
    HSSFCellStyle style = workbook.createCellStyle();
    style.setWrapText(true);/*from  www. j  ava 2  s .c  o m*/
    HSSFFont font = workbook.createFont();
    font.setFontName("Courier New");
    style.setFont(font);
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    style.setBorderTop(HSSFCellStyle.BORDER_THIN);
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

    // Header Style
    HSSFCellStyle styleHeader = workbook.createCellStyle();
    styleHeader.cloneStyleFrom(style);
    styleHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    font = workbook.createFont();
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    font.setColor(HSSFColor.WHITE.index);
    styleHeader.setFillForegroundColor(IndexedColors.BLACK.getIndex());
    styleHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    styleHeader.setFont(font);

    // Error Style
    HSSFCellStyle styleError = workbook.createCellStyle();
    styleError.cloneStyleFrom(style);
    styleError.setFillForegroundColor(IndexedColors.CORAL.getIndex());
    styleError.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    styleError.setWrapText(true);

    // Link Style
    HSSFCellStyle styleLink = workbook.createCellStyle();
    styleLink.cloneStyleFrom(style);
    font = workbook.createFont();
    font.setUnderline(HSSFFont.U_SINGLE);
    font.setColor(IndexedColors.BLUE.getIndex());
    styleLink.setFont(font);

    // Create Summary
    HSSFSheet summarySheet = workbook.createSheet("Summary");
    int summaryRownum = 0;
    int summaryCellnum = 0;

    //Create a new row in current sheet
    Row summaryRow = summarySheet.createRow(summaryRownum++);

    // 0
    Cell summaryCell = summaryRow.createCell(summaryCellnum++);
    summaryCell.setCellValue("Job");
    summaryCell.setCellStyle(styleHeader);

    // 1
    summaryCell = summaryRow.createCell(summaryCellnum++);
    summaryCell.setCellValue("Finished");
    summaryCell.setCellStyle(styleHeader);

    // 2
    summaryCell = summaryRow.createCell(summaryCellnum++);
    summaryCell.setCellValue("Errors");
    summaryCell.setCellStyle(styleHeader);

    for (Job job : releaseService.getJobs()) {

        // Open Job
        JobService jobService = new JobService(siteService.getSiteName(), job.getJobName());

        // Create Sheet
        HSSFSheet sheet = workbook.createSheet(job.getJobName());

        int rownum = 0;
        int cellnum = 0;
        int errors = 0;

        //Create a new row in current sheet
        Row row = sheet.createRow(rownum++);

        // 0
        Cell cell = row.createCell(cellnum++);
        cell.setCellValue("Host");
        cell.setCellStyle(styleHeader);

        // 1
        cell = row.createCell(cellnum++);
        cell.setCellValue("Service");
        cell.setCellStyle(styleHeader);

        // 2
        cell = row.createCell(cellnum++);
        cell.setCellValue("Command");
        cell.setCellStyle(styleHeader);

        // 3
        cell = row.createCell(cellnum++);
        cell.setCellValue("Executable");
        cell.setCellStyle(styleHeader);

        // 4
        cell = row.createCell(cellnum++);
        cell.setCellValue("Error");
        cell.setCellStyle(styleHeader);

        // 5
        cell = row.createCell(cellnum++);
        cell.setCellValue("Output");
        cell.setCellStyle(styleHeader);

        // Check all hosts
        for (Host host : jobService.getHosts()) {

            // Check all services
            for (Service service : host.getServices()) {

                // Get a Commands
                for (Command command : service.getCommands()) {

                    //Create a new row in current sheet
                    row = sheet.createRow(rownum++);
                    cellnum = 0;

                    // 0
                    cell = row.createCell(cellnum++);
                    cell.setCellValue(host.getHostName());
                    cell.setCellStyle(style);

                    // 1
                    cell = row.createCell(cellnum++);
                    cell.setCellValue(service.getServiceName());
                    cell.setCellStyle(style);

                    // 2
                    cell = row.createCell(cellnum++);
                    cell.setCellValue(command.getTitle());
                    cell.setCellStyle(style);

                    // 3
                    cell = row.createCell(cellnum++);
                    cell.setCellValue(command.getExec());
                    cell.setCellStyle(style);

                    // 4
                    cell = row.createCell(cellnum++);
                    cell.setCellValue("N");
                    cell.setCellStyle(style);

                    // 5
                    cell = row.createCell(cellnum++);
                    if (command.getOut().length() > 1024) {
                        cell.setCellValue(command.getOut().substring(0, 1024) + "...");
                    } else {
                        cell.setCellValue(command.getOut());
                    }
                    cell.setCellStyle(style);

                    // Error
                    if (command.isError() == true) {
                        row.getCell(0).setCellStyle(styleError);
                        row.getCell(1).setCellStyle(styleError);
                        row.getCell(2).setCellStyle(styleError);
                        row.getCell(3).setCellStyle(styleError);
                        row.getCell(4).setCellStyle(styleError);
                        row.getCell(5).setCellStyle(styleError);
                        row.getCell(4).setCellValue("Y");
                        errors++;
                    }
                }
            }
        }

        // Set Size
        sheet.setColumnWidth(0, 6000);
        sheet.setColumnWidth(1, 4000);
        sheet.setColumnWidth(2, 8000);
        sheet.setColumnWidth(3, 14000);
        sheet.setColumnWidth(4, 3000);
        sheet.setColumnWidth(5, 20000);

        // Summary
        summaryRow = summarySheet.createRow(summaryRownum++);
        summaryCellnum = 0;

        // 0
        summaryCell = summaryRow.createCell(summaryCellnum++);
        summaryCell.setCellValue(job.getJobName());
        summaryCell.setCellStyle(style);

        // Set Link
        HSSFHyperlink link = creationHelper.createHyperlink(Hyperlink.LINK_DOCUMENT);
        link.setAddress("" + job.getJobName() + "!A1");
        summaryCell.setHyperlink(link);
        summaryCell.setCellStyle(styleLink);

        // 1
        summaryCell = summaryRow.createCell(summaryCellnum++);
        summaryCell.setCellValue(jobService.getJob().getFinished());
        summaryCell.setCellStyle(style);

        // 2
        summaryCell = summaryRow.createCell(summaryCellnum++);
        summaryCell.setCellValue(errors);
        summaryCell.setCellStyle(style);

        // If errors found
        if (errors > 0) {
            summaryRow.getCell(0).setCellStyle(styleError);
            summaryRow.getCell(1).setCellStyle(styleError);
            summaryRow.getCell(2).setCellStyle(styleError);
        }
    }

    // Set Summary Size
    summarySheet.setColumnWidth(0, 6000);
    summarySheet.setColumnWidth(1, 10000);
    summarySheet.setColumnWidth(2, 4000);

    // Save
    try {
        FileOutputStream out = new FileOutputStream(new File(getFileName()));
        workbook.write(out);
        out.close();
        logger.log(Level.INFO, "{0} generated successfully..", getFileName());

        return workbook;
    } catch (FileNotFoundException ex) {
        logger.log(Level.WARNING, "Audit: {0}", ex);
    } catch (IOException ex) {
        logger.log(Level.WARNING, "Audit: {0}", ex);
    }

    return null;
}

From source file:org.displaytag.export.excel.ExcelUtils.java

License:Open Source License

/**
 * We cache the styles; they are expensive to construct.
 * @param properties props for this run//from   www  . j a v a 2 s  . com
 */
public void initCellStyles(TableProperties properties) {
    // Integer
    HSSFCellStyle style = getNewCellStyle();
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setDataFormat(
            HSSFDataFormat.getBuiltinFormat(properties.getProperty(ExcelUtils.EXCEL_FORMAT_INTEGER)));
    this.cellStyles.put(STYLE_INTEGER, style);

    // NUMBER
    style = getNewCellStyle();
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setDataFormat(
            HSSFDataFormat.getBuiltinFormat(properties.getProperty(ExcelUtils.EXCEL_FORMAT_NUMBER)));
    this.cellStyles.put(STYLE_NUMBER, style);

    // style = HSSFDataFormat.getBuiltinFormat("0.00%");

    // Date
    style = getNewCellStyle();
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    style.setDataFormat(HSSFDataFormat.getBuiltinFormat(properties.getProperty(ExcelUtils.EXCEL_FORMAT_DATE)));
    style.setAlignment(CellStyle.ALIGN_RIGHT);
    this.cellStyles.put(STYLE_DATE, style);

    // Long text
    style = getNewCellStyle(); // http://jakarta.apache.org/poi/hssf/quick-guide.html#NewLinesInCells
    style.setWrapText(true);
    this.cellStyles.put(STYLE_LONGSTRING, style);

    // Regular text
    this.cellStyles.put(STYLE_STRING, getNewCellStyle());

    this.wrapAt = Integer.valueOf(properties.getProperty(ExcelUtils.EXCEL_WRAPAT));
}

From source file:org.displaytag.render.HssfTableWriter.java

License:Open Source License

/**
 * @see org.displaytag.render.TableWriterTemplate#writeCaption(org.displaytag.model.TableModel)
 *//*w w w  .  j  ava 2  s  .  c o  m*/
@Override
protected void writeCaption(TableModel model) throws Exception {
    HSSFCellStyle style = this.wb.createCellStyle();
    HSSFFont bold = this.wb.createFont();
    bold.setBoldweight(Font.BOLDWEIGHT_BOLD);
    bold.setFontHeightInPoints((short) 14);
    style.setFont(bold);
    style.setAlignment(CellStyle.ALIGN_CENTER);

    this.colNum = 0;
    this.currentRow = this.sheet.createRow(this.sheetRowNum++);
    this.currentCell = this.currentRow.createCell(this.colNum);
    this.currentCell.setCellStyle(style);
    String caption = model.getCaption();
    this.currentCell.setCellValue(new HSSFRichTextString(caption));
    this.rowSpanTable(model);
}

From source file:org.extremecomponents.table.view.ExtendXlsView.java

License:Apache License

private Map initStyles(HSSFWorkbook wb, short fontHeight) {
    Map result = new HashMap();
    HSSFCellStyle titleStyle = wb.createCellStyle();
    HSSFCellStyle textStyle = wb.createCellStyle();
    HSSFCellStyle boldStyle = wb.createCellStyle();
    HSSFCellStyle numericStyle = wb.createCellStyle();
    HSSFCellStyle numericStyleBold = wb.createCellStyle();
    HSSFCellStyle moneyStyle = wb.createCellStyle();
    HSSFCellStyle moneyStyleBold = wb.createCellStyle();
    HSSFCellStyle percentStyle = wb.createCellStyle();
    HSSFCellStyle percentStyleBold = wb.createCellStyle();

    result.put("titleStyle", titleStyle);
    result.put("textStyle", textStyle);
    result.put("boldStyle", boldStyle);
    result.put("numericStyle", numericStyle);
    result.put("numericStyleBold", numericStyleBold);
    result.put("moneyStyle", moneyStyle);
    result.put("moneyStyleBold", moneyStyleBold);
    result.put("percentStyle", percentStyle);
    result.put("percentStyleBold", percentStyleBold);

    HSSFDataFormat format = wb.createDataFormat();

    // Global fonts
    HSSFFont font = wb.createFont();//from w  w w.ja  va  2 s .co  m
    font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
    font.setColor(HSSFColor.BLACK.index);
    font.setFontName(HSSFFont.FONT_ARIAL);
    font.setFontHeightInPoints(fontHeight);

    HSSFFont fontBold = wb.createFont();
    fontBold.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    fontBold.setColor(HSSFColor.BLACK.index);
    fontBold.setFontName(HSSFFont.FONT_ARIAL);
    fontBold.setFontHeightInPoints(fontHeight);

    // Money Style
    moneyStyle.setFont(font);
    moneyStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    moneyStyle.setDataFormat(format.getFormat(moneyFormat));

    // Money Style Bold
    moneyStyleBold.setFont(fontBold);
    moneyStyleBold.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    moneyStyleBold.setDataFormat(format.getFormat(moneyFormat));

    // Percent Style
    percentStyle.setFont(font);
    percentStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    percentStyle.setDataFormat(format.getFormat(percentFormat));

    // Percent Style Bold
    percentStyleBold.setFont(fontBold);
    percentStyleBold.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    percentStyleBold.setDataFormat(format.getFormat(percentFormat));

    // Standard Numeric Style
    numericStyle.setFont(font);
    numericStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);

    // Standard Numeric Style Bold
    numericStyleBold.setFont(fontBold);
    numericStyleBold.setAlignment(HSSFCellStyle.ALIGN_RIGHT);

    // Title Style
    titleStyle.setFont(font);
    titleStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    titleStyle.setBottomBorderColor(HSSFColor.BLACK.index);
    titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    titleStyle.setLeftBorderColor(HSSFColor.BLACK.index);
    titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
    titleStyle.setRightBorderColor(HSSFColor.BLACK.index);
    titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
    titleStyle.setTopBorderColor(HSSFColor.BLACK.index);
    titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

    // Standard Text Style
    textStyle.setFont(font);
    textStyle.setWrapText(true);

    // Standard Text Style
    boldStyle.setFont(fontBold);
    boldStyle.setWrapText(true);

    return result;
}

From source file:org.fenixedu.academic.ui.struts.action.academicAdministration.executionCourseManagement.CourseLoadOverviewBean.java

License:Open Source License

public StyledExcelSpreadsheet getInconsistencySpreadsheet() {
    final StyledExcelSpreadsheet spreadsheet = new StyledExcelSpreadsheet(
            BundleUtil.getString(Bundle.ACADEMIC, "label.course.load.inconsistency.filename") + "_"
                    + executionSemester.getExecutionYear().getYear().replace('/', '_') + "_"
                    + executionSemester.getSemester());
    CellStyle normalStyle = spreadsheet.getExcelStyle().getValueStyle();
    normalStyle.setAlignment(HorizontalAlignment.CENTER);

    HSSFWorkbook wb = spreadsheet.getWorkbook();
    HSSFFont font = wb.createFont();//from   www.j a  va 2 s .  c  o  m
    font.setColor(HSSFColor.BLACK.index);
    font.setFontHeightInPoints((short) 8);
    HSSFCellStyle redStyle = wb.createCellStyle();
    redStyle.setFont(font);
    redStyle.setAlignment(HorizontalAlignment.CENTER);
    redStyle.setFillForegroundColor(HSSFColor.ORANGE.index);
    redStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    HSSFCellStyle yellowStyle = wb.createCellStyle();
    yellowStyle.setFont(font);
    yellowStyle.setAlignment(HorizontalAlignment.CENTER);
    yellowStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
    yellowStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

    spreadsheet.newHeaderRow();
    spreadsheet.addHeader(BundleUtil.getString(Bundle.ACADEMIC, "label.department"));
    spreadsheet.addHeader(BundleUtil.getString(Bundle.ACADEMIC, "label.degree"));
    spreadsheet.addHeader(BundleUtil.getString(Bundle.ACADEMIC, "label.executionCourse"));
    spreadsheet.addHeader(BundleUtil.getString(Bundle.ACADEMIC, "label.shift"));
    spreadsheet.addHeader(BundleUtil.getString(Bundle.ACADEMIC, "label.shiftType"));
    spreadsheet.addHeader(BundleUtil.getString(Bundle.ACADEMIC, "label.load.competenceCourse"));
    spreadsheet.addHeader(BundleUtil.getString(Bundle.ACADEMIC, "label.load.curricularCourse"));
    spreadsheet.addHeader(BundleUtil.getString(Bundle.ACADEMIC, "label.load.executionCourse"));
    spreadsheet.addHeader(BundleUtil.getString(Bundle.ACADEMIC, "label.load.lessonInstances"));
    spreadsheet.addHeader(BundleUtil.getString(Bundle.ACADEMIC, "label.load.lesson.count"));
    spreadsheet.addHeader(BundleUtil.getString(Bundle.ACADEMIC, "label.load.lessonInstances.count"));

    for (final ExecutionCourse executionCourse : executionSemester.getAssociatedExecutionCoursesSet()) {
        for (final CourseLoad courseLoad : executionCourse.getCourseLoadsSet()) {
            for (final Shift shift : courseLoad.getShiftsSet()) {
                spreadsheet.newRow();
                spreadsheet.addCell(getDepartmentString(executionCourse));
                spreadsheet.addCell(executionCourse.getDegreePresentationString());
                spreadsheet.addCell(executionCourse.getName());
                spreadsheet.addCell(shift.getNome());
                spreadsheet.addCell(courseLoad.getType().getFullNameTipoAula());
                final BigDecimal competenceCourseLoad = new BigDecimal(getCompetenceCourseLoad(courseLoad))
                        .setScale(2, RoundingMode.HALF_EVEN);
                final BigDecimal curricularCourseLoad = new BigDecimal(getCurricularCourseLoad(courseLoad))
                        .setScale(2, RoundingMode.HALF_EVEN);
                final BigDecimal executionLoad = courseLoad.getTotalQuantity().setScale(2,
                        RoundingMode.HALF_EVEN);
                final BigDecimal shiftCourseLoad = getShiftCourseLoad(shift).setScale(2,
                        RoundingMode.HALF_EVEN);
                if (competenceCourseLoad.signum() < 0) {
                    spreadsheet.addCell(getCompetenceCourseLoadStrings(courseLoad), redStyle);
                } else {
                    spreadsheet.addCell(competenceCourseLoad);
                }
                if (!competenceCourseLoad.equals(curricularCourseLoad) || curricularCourseLoad.signum() < 0) {
                    spreadsheet.addCell(getCurricularCourseLoadString(courseLoad), redStyle);
                } else {
                    spreadsheet.addCell(curricularCourseLoad);
                }
                if (!executionLoad.equals(curricularCourseLoad)) {
                    spreadsheet.addCell(executionLoad, redStyle);
                } else {
                    spreadsheet.addCell(executionLoad);
                }
                if (!shiftCourseLoad.equals(executionLoad)) {
                    if (isLargeDifference(shiftCourseLoad, executionLoad,
                            competenceCourseLoad.divide(new BigDecimal(14), 2, RoundingMode.HALF_EVEN))) {
                        spreadsheet.addCell(shiftCourseLoad, redStyle);
                    } else {
                        spreadsheet.addCell(shiftCourseLoad, yellowStyle);
                    }
                } else {
                    spreadsheet.addCell(shiftCourseLoad);
                }
                spreadsheet.addCell(shift.getAssociatedLessonsSet().size());
                spreadsheet.addCell(getLessonInstanceCount(shift));
            }
        }
    }

    final HSSFSheet sheet = wb.getSheetAt(0);
    sheet.createFreezePane(0, 1, 0, 1);
    sheet.autoSizeColumn(1, true);
    sheet.autoSizeColumn(2, true);
    sheet.autoSizeColumn(3, true);
    sheet.autoSizeColumn(4, true);
    sheet.autoSizeColumn(5, true);
    sheet.autoSizeColumn(6, true);
    sheet.autoSizeColumn(7, true);
    sheet.autoSizeColumn(8, true);
    sheet.autoSizeColumn(9, true);

    return spreadsheet;
}