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

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

Introduction

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

Prototype

@Override
public void setFillPattern(FillPatternType fp) 

Source Link

Document

setting to one fills the cell with the foreground color...

Usage

From source file:net.mindengine.oculus.frontend.service.report.ExcelTestSearchReportGenerator.java

License:Open Source License

/**
 * Generates Excel spreadsheet./* w  w  w  .ja  va 2  s. c om*/
 *
 * @param searchResult Search result for test or document (test-case)
 * @throws Exception 
 */
public void writeExcelReports(BrowseResult<?> searchResult, Long projectId, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    int cellOffset = 5;
    /*
     * Customizations which will be exported to XLS spreadsheet.
     */
    Collection<Customization> customizationsExport = new LinkedList<Customization>();

    /*
     * Here will be cell ids stored for each customization. This is needed because there might be a lot of merged cells for list customizations
     */
    Map<Long, Integer> customizationCells = new HashMap<Long, Integer>();

    if (projectId != null && projectId > 0) {
        Collection<Customization> customizations = customizationDAO.getCustomizations(projectId, unit);
        for (Customization customization : customizations) {

            //Checking if the user has selected this specific customization for exporting
            if ("on".equals(request.getParameter("cexport" + customization.getId()))) {

                customizationCells.put(customization.getId(), cellOffset);

                //Checking if the customization contains possible values and fetching them all
                if (customization.getType().equals(Customization.TYPE_CHECKLIST)
                        || customization.getType().equals(Customization.TYPE_LIST)) {
                    customization.setPossibleValues(
                            customizationDAO.getCustomizationPossibleValues(customization.getId()));
                    cellOffset += customization.getPossibleValues().size();
                } else {
                    cellOffset += 1;
                }

                customizationsExport.add(customization);
            }
        }
    }

    /*
     * Generating the Excel spreadsheet
     */

    OutputStream outputStream = response.getOutputStream();
    response.setContentType("application/ms-excel");

    HSSFWorkbook workBook = new HSSFWorkbook();

    HSSFSheet sheet = workBook.createSheet();

    HSSFFont fontHeader = workBook.createFont();
    fontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    fontHeader.setColor(HSSFColor.WHITE.index);

    HSSFCellStyle columnHeaderStyle = workBook.createCellStyle();
    columnHeaderStyle.setBorderTop((short) 2);
    columnHeaderStyle.setBorderLeft((short) 2);
    columnHeaderStyle.setBorderRight((short) 2);
    columnHeaderStyle.setBorderBottom((short) 2);
    columnHeaderStyle.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index);
    columnHeaderStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

    columnHeaderStyle.setFont(fontHeader);

    HSSFCellStyle columnRootHeaderStyle = workBook.createCellStyle();

    //columnRootHeaderStyle.cloneStyleFrom(columnHeaderStyle);
    columnRootHeaderStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

    HSSFCell cell;

    HSSFRow headerRow = sheet.createRow(0);
    HSSFRow header2Row = sheet.createRow(1);

    sheet.addMergedRegion(new Region((short) 0, (short) 0, (short) 0, (short) 4));
    cell = headerRow.createCell((short) 0);
    cell.setCellValue("Common");
    cell.setCellStyle(columnRootHeaderStyle);

    cell = header2Row.createCell((short) 0);
    cell.setCellValue("Test");
    cell.setCellStyle(columnHeaderStyle);

    cell = header2Row.createCell((short) 1);
    cell.setCellValue("Project");
    cell.setCellStyle(columnHeaderStyle);

    cell = header2Row.createCell((short) 2);
    cell.setCellValue("Sub-Project");
    cell.setCellStyle(columnHeaderStyle);

    cell = header2Row.createCell((short) 3);
    cell.setCellValue("Author");
    cell.setCellStyle(columnHeaderStyle);

    cell = header2Row.createCell((short) 4);
    cell.setCellValue("Created");
    cell.setCellStyle(columnHeaderStyle);

    for (Customization customization : customizationsExport) {
        int cellId = customizationCells.get(customization.getId());
        if (customization.getPossibleValues() != null) {
            int size = customization.getPossibleValues().size();
            if (size > 1) {
                sheet.addMergedRegion(
                        new Region((short) 0, (short) 0, (short) cellId, (short) (cellId + size - 1)));
            }

            /*
             * Exporting possible values 
             */
            int offset = 0;
            for (CustomizationPossibleValue cpv : customization.getPossibleValues()) {
                cell = header2Row.createCell((short) (cellId + offset));
                cell.setCellValue(cpv.getPossibleValue());
                cell.setCellStyle(columnHeaderStyle);
                offset++;
            }
        } else {
            cell = header2Row.createCell((short) cellId);
            cell.setCellStyle(columnHeaderStyle);
        }
        cell = headerRow.createCell((short) cellId);
        cell.setCellValue(customization.getName());
        cell.setCellStyle(columnRootHeaderStyle);
    }

    HSSFCellStyle cellStyle = workBook.createCellStyle();

    HSSFCellStyle checkboxStyle = workBook.createCellStyle();
    checkboxStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
    checkboxStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    checkboxStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

    HSSFFont fontCheckbox = workBook.createFont();
    fontCheckbox.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    fontCheckbox.setColor(HSSFColor.BLACK.index);
    checkboxStyle.setFont(fontCheckbox);

    HSSFCellStyle boolYesStyle = workBook.createCellStyle();
    boolYesStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
    boolYesStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

    HSSFCellStyle boolNoStyle = workBook.createCellStyle();
    boolNoStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);
    boolNoStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

    /*
     * Used in order to cache user names. Key = ID, Value = User name
     */
    Map<Long, String> usersCache = new HashMap<Long, String>();

    int j = 2;
    for (Object object : searchResult.getResults()) {
        HSSFRow row = sheet.createRow(j);

        String name, parentProjectName, projectName, authorName;
        Date date;
        Long objectId;

        if (object instanceof Test) {
            Test test = (Test) object;
            name = test.getName();
            parentProjectName = test.getParentProjectName();
            projectName = test.getProjectName();
            authorName = test.getAuthorName();
            objectId = test.getId();
            date = test.getDate();
        } else
            throw new IllegalArgumentException(object.getClass().getName());

        cell = row.createCell((short) 0);
        cell.setCellValue(name);
        cell.setCellStyle(cellStyle);

        cell = row.createCell((short) 1);
        cell.setCellValue(parentProjectName);
        cell.setCellStyle(cellStyle);

        cell = row.createCell((short) 2);
        cell.setCellValue(projectName);
        cell.setCellStyle(cellStyle);

        cell = row.createCell((short) 3);
        cell.setCellValue(authorName);
        cell.setCellStyle(cellStyle);

        cell = row.createCell((short) 4);
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        cell.setCellValue(sdf.format(date));
        cell.setCellStyle(cellStyle);

        int offset = 5;

        for (Customization customization : customizationsExport) {
            UnitCustomizationValue ucv = customizationDAO.getUnitCustomizationValue(customization.getId(),
                    objectId);

            if (customization.getType().equals(Customization.TYPE_CHECKLIST)
                    || customization.getType().equals(Customization.TYPE_LIST)) {
                for (CustomizationPossibleValue cpv : customization.getPossibleValues()) {

                    boolean matches = false;

                    if (customization.getType().equals(Customization.TYPE_LIST)) {
                        if (ucv != null && ucv.getValue() != null && ucv.getValue().equals("" + cpv.getId())) {
                            matches = true;
                        }
                    } else {
                        String s = "(" + cpv.getId() + ")";
                        if (ucv != null && ucv.getValue() != null && ucv.getValue().contains(s)) {
                            matches = true;
                        }
                    }

                    if (matches) {
                        cell = row.createCell((short) offset);
                        cell.setCellValue("X");
                        cell.setCellStyle(checkboxStyle);
                    }
                    offset++;
                }
            } else {
                if (ucv != null) {
                    cell = row.createCell((short) offset);
                    cell.setCellStyle(cellStyle);

                    if (customization.getType().equals(Customization.TYPE_ASSIGNEE)) {
                        if (ucv.getValue() != null && !ucv.getValue().isEmpty()) {
                            try {
                                Long userId = Long.parseLong(ucv.getValue());
                                /*
                                 * Chaching user names by their ids
                                 */
                                String userName = null;
                                if (!usersCache.containsKey(userId)) {
                                    User user = userDAO.getUserById(userId);
                                    if (user != null) {
                                        userName = user.getName();
                                    } else
                                        userName = "";

                                    usersCache.put(userId, userName);
                                } else
                                    userName = usersCache.get(userId);

                                cell.setCellValue(userName);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else if (customization.getType().equals(Customization.TYPE_CHECKBOX)) {
                        if (ucv.getValue() != null) {
                            if (ucv.getValue().equals("true")) {
                                cell.setCellValue("Yes");
                                cell.setCellStyle(boolYesStyle);
                            } else {
                                cell.setCellValue("No");
                                cell.setCellStyle(boolNoStyle);
                            }
                        }
                    } else {
                        cell.setCellValue(ucv.getValue());
                    }

                }
                offset++;
            }
        }
        j++;
    }

    /*
     * Making the text to fit in all cells 
     */
    for (short i = 0; i < (short) cellOffset + 1; i++) {
        sheet.autoSizeColumn(i);
    }

    workBook.write(outputStream);
    outputStream.flush();
    outputStream.close();
}

From source file:net.sf.jasperreports.engine.export.JRXlsExporter.java

License:Open Source License

protected HSSFCellStyle getLoadedCellStyle(StyleInfo style) {
    HSSFCellStyle cellStyle = loadedCellStyles.get(style);
    if (cellStyle == null) {
        cellStyle = workbook.createCellStyle();

        cellStyle.setFillForegroundColor(style.backcolor);
        cellStyle.setFillPattern(style.mode);
        cellStyle.setAlignment(style.horizontalAlignment);
        cellStyle.setVerticalAlignment(style.verticalAlignment);
        cellStyle.setRotation(style.rotation);
        cellStyle.setFont(style.font);//from   ww  w .ja  v a 2s  .  c  o m
        cellStyle.setWrapText(style.lcWrapText);
        cellStyle.setLocked(style.lcCellLocked);
        cellStyle.setHidden(style.lcCellHidden);

        if (style.hasDataFormat()) {
            cellStyle.setDataFormat(style.getDataFormat());
        }

        boolean isIgnoreCellBorder = getCurrentItemConfiguration().isIgnoreCellBorder();
        if (!isIgnoreCellBorder) {
            BoxStyle box = style.box;
            cellStyle.setBorderTop(box.borderStyle[BoxStyle.TOP]);
            cellStyle.setTopBorderColor(box.borderColour[BoxStyle.TOP]);
            cellStyle.setBorderLeft(box.borderStyle[BoxStyle.LEFT]);
            cellStyle.setLeftBorderColor(box.borderColour[BoxStyle.LEFT]);
            cellStyle.setBorderBottom(box.borderStyle[BoxStyle.BOTTOM]);
            cellStyle.setBottomBorderColor(box.borderColour[BoxStyle.BOTTOM]);
            cellStyle.setBorderRight(box.borderStyle[BoxStyle.RIGHT]);
            cellStyle.setRightBorderColor(box.borderColour[BoxStyle.RIGHT]);
        }

        loadedCellStyles.put(style, cellStyle);
    }
    return cellStyle;
}

From source file:net.sf.jasperreports.engine.export.JRXlsMetadataExporter.java

License:Open Source License

protected HSSFCellStyle getLoadedCellStyle(StyleInfo style) {
    HSSFCellStyle cellStyle = loadedCellStyles.get(style);
    if (cellStyle == null) {

        cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(style.backcolor);
        cellStyle.setFillPattern(style.mode);
        cellStyle.setAlignment(style.horizontalAlignment);
        cellStyle.setVerticalAlignment(style.verticalAlignment);
        cellStyle.setRotation(style.rotation);
        cellStyle.setFont(style.font);// w  w  w .j  ava  2  s . co m
        cellStyle.setWrapText(style.lcWrapText);
        cellStyle.setLocked(style.lcCellLocked);
        cellStyle.setHidden(style.lcCellHidden);

        if (style.hasDataFormat()) {
            cellStyle.setDataFormat(style.getDataFormat());
        }

        if (!getCurrentItemConfiguration().isIgnoreCellBorder()) {
            BoxStyle box = style.box;
            cellStyle.setBorderTop(box.borderStyle[BoxStyle.TOP]);
            cellStyle.setTopBorderColor(box.borderColour[BoxStyle.TOP]);
            cellStyle.setBorderLeft(box.borderStyle[BoxStyle.LEFT]);
            cellStyle.setLeftBorderColor(box.borderColour[BoxStyle.LEFT]);
            cellStyle.setBorderBottom(box.borderStyle[BoxStyle.BOTTOM]);
            cellStyle.setBottomBorderColor(box.borderColour[BoxStyle.BOTTOM]);
            cellStyle.setBorderRight(box.borderStyle[BoxStyle.RIGHT]);
            cellStyle.setRightBorderColor(box.borderColour[BoxStyle.RIGHT]);
        }
        loadedCellStyles.put(style, cellStyle);
    }
    return cellStyle;
}

From source file:net.sourceforge.fenixedu.presentationTier.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());
    HSSFCellStyle normalStyle = spreadsheet.getExcelStyle().getValueStyle();
    normalStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

    HSSFWorkbook wb = spreadsheet.getWorkbook();
    HSSFFont font = wb.createFont();/*from w  ww.j av a2  s  .  co m*/
    font.setColor(HSSFColor.BLACK.index);
    font.setFontHeightInPoints((short) 8);
    HSSFCellStyle redStyle = wb.createCellStyle();
    redStyle.setFont(font);
    redStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    redStyle.setFillForegroundColor(HSSFColor.ORANGE.index);
    redStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    HSSFCellStyle yellowStyle = wb.createCellStyle();
    yellowStyle.setFont(font);
    yellowStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    yellowStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
    yellowStyle.setFillPattern(HSSFCellStyle.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;
}

From source file:net.triptech.buildulator.view.ExcelTemplateView.java

License:Open Source License

@Override
protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    DataGrid dataGrid = (DataGrid) model.get("dataGrid");

    String sheetName = "Sheet 1";
    if (StringUtils.isNotBlank(dataGrid.getTitle())) {
        sheetName = dataGrid.getTitle();
    }//from  www . j  ava2s  .c o  m

    HSSFSheet sheet = workbook.createSheet(sheetName);

    Font font = workbook.createFont();
    font.setColor(HSSFColor.WHITE.index);

    HSSFCellStyle style = workbook.createCellStyle();
    style.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index);
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    style.setFont(font);

    int rowNum = 0;
    int maxColumnCount = 0;

    if (dataGrid.getHeaderFields().size() > 0) {
        HSSFRow header = sheet.createRow(rowNum);
        rowNum++;

        maxColumnCount = dataGrid.getHeaderFields().size();

        int i = 0;
        for (String field : dataGrid.getHeaderFields()) {

            HSSFCell cell = header.createCell(i);
            cell.setCellValue(field);
            cell.setCellStyle(style);
            i++;
        }
    }

    for (int y = 0; y < dataGrid.getRowCount(); y++) {
        HSSFRow row = sheet.createRow(rowNum++);

        List<String> rowData = dataGrid.getRowFields(y);

        if (rowData.size() > maxColumnCount) {
            maxColumnCount = rowData.size();
        }

        int x = 0;

        for (String data : rowData) {
            HSSFCell cell = row.createCell(x);

            try {
                double dbValue = Double.parseDouble(data);
                cell.setCellValue(dbValue);
            } catch (NumberFormatException nfe) {
                cell.setCellValue(data);
            }
            x++;
        }
    }

    for (int i = 0; i < maxColumnCount; i++) {
        sheet.autoSizeColumn(i);
    }
}

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  w  w .j  a  v a  2s  . c  o m*/
    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.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 . ja  v  a 2 s  . co m
 * @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>//w  w  w.j av a  2 s  .  c o 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();//  w ww.jav a  2 s. 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  w ww.j  a  v a  2s.  c  om
    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;
}