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:org.displaytag.export.excel.ExcelHssfView.java

License:Open Source License

/**
 * Templated method that is called for all header cells.
 *
 * @param wb the wb/*w w  w. j av  a2 s .com*/
 * @param headerCell the header cell
 * @return the HSSF cell style
 */
public HSSFCellStyle createHeaderStyle(HSSFWorkbook wb, HeaderCell headerCell) {
    HSSFCellStyle headerStyle = getNewCellStyle();

    headerStyle.setFillPattern(CellStyle.FINE_DOTS);
    headerStyle.setFillBackgroundColor(HSSFColor.BLUE_GREY.index);
    HSSFFont bold = wb.createFont();
    bold.setBoldweight(Font.BOLDWEIGHT_BOLD);
    bold.setColor(HSSFColor.WHITE.index);
    headerStyle.setFont(bold);

    return headerStyle;
}

From source file:org.egov.infra.web.displaytag.export.EGovExcelReadOnlyView.java

License:Open Source License

/**
 * @see org.displaytag.export.BinaryExportView#doExport(OutputStream)
 *//* w w  w. j  av  a2  s.  co m*/
@Override
public void doExport(final OutputStream out) throws JspException {
    try {
        final HSSFWorkbook wb = new HSSFWorkbook();
        wb.writeProtectWorkbook("egov", "egov");// To make the workbook read-only
        this.sheet = wb.createSheet("-");

        int rowNum = 0;
        int colNum = 0;

        if (this.header) {
            // Create an header row
            final HSSFRow xlsRow = this.sheet.createRow(rowNum++);

            final HSSFCellStyle headerStyle = wb.createCellStyle();
            headerStyle.setFillPattern(HSSFCellStyle.FINE_DOTS);
            headerStyle.setFillBackgroundColor(HSSFColor.BLUE_GREY.index);
            final HSSFFont bold = wb.createFont();
            bold.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            bold.setColor(HSSFColor.WHITE.index);
            headerStyle.setFont(bold);

            final Iterator iterator = this.model.getHeaderCellList().iterator();

            while (iterator.hasNext()) {
                final HeaderCell headerCell = (HeaderCell) iterator.next();

                String columnHeader = headerCell.getTitle();

                if (columnHeader == null) {
                    columnHeader = StringUtils.capitalize(headerCell.getBeanPropertyName());
                }

                final HSSFCell cell = xlsRow.createCell(colNum++);
                cell.setCellValue(escapeColumnValue(columnHeader));
                cell.setCellStyle(headerStyle);
            }
        }

        // get the correct iterator (full or partial list according to the exportFull field)
        final RowIterator rowIterator = this.model.getRowIterator(this.exportFull);

        // iterator on rows
        while (rowIterator.hasNext()) {
            final Row row = rowIterator.next();
            final HSSFRow xlsRow = this.sheet.createRow(rowNum++);
            colNum = 0;

            // iterator on columns
            final ColumnIterator columnIterator = row.getColumnIterator(this.model.getHeaderCellList());

            while (columnIterator.hasNext()) {
                final Column column = columnIterator.nextColumn();

                // Get the value to be displayed for the column
                final Object value = column.getValue(this.decorated);

                final HSSFCell cell = xlsRow.createCell(colNum++);

                if (value instanceof Number) {
                    final Number num = (Number) value;
                    cell.setCellValue(num.doubleValue());
                } else if (value instanceof Date) {
                    cell.setCellValue((Date) value);
                } else if (value instanceof Calendar) {
                    cell.setCellValue((Calendar) value);
                } else {
                    cell.setCellValue(escapeColumnValue(value));
                }
            }
        }

        for (short i = 0; i < colNum; i++) {
            this.sheet.autoSizeColumn(i, true);
        }
        wb.write(out);
    } catch (final Exception e) {
        throw new ExcelGenerationException(e);
    }
}

From source file:org.emmanet.controllers.statsSpreadsheetController.java

License:Apache License

public boolean createHeaderCells(HSSFWorkbook arg1, HSSFSheet sheet, String[] fieldNames) {

    headerTitle = fieldNames;//from  w  w  w.  j ava 2  s  . co  m
    HSSFRow header = sheet.createRow(0);

    /**********************************************
     *
     *  CELL HEADER STYLE
     * 
     * ********************************************
     */
    HSSFCellStyle style = arg1.createCellStyle();
    style.setFillBackgroundColor(HSSFColor.AQUA.index);
    style.setFillForegroundColor(HSSFColor.WHITE.index);
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

    for (int i = 0; i < headerTitle.length; i++) {
        HSSFRichTextString richString = new HSSFRichTextString(headerTitle[i]);
        HSSFCell cell = header.createCell((short) i);
        cell.setCellStyle(style);
        cell.setCellValue(richString);
    }

    return true;
}

From source file:org.emmanet.util.CreateSpreadsheet.java

License:Apache License

protected void buildExcelDocument(Map map, HSSFWorkbook wb, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws Exception {

    data = (List) map.get("data");
    columns = (List) map.get("columns");
    String sheets[] = (String[]) map.get("sheets");
    int freeze = 1;
    String filename = (String) map.get("filename");

    // set list values
    if (filename.equals("stats")) {

        System.out.println("################################################# create spreadsheet called");

        /* Due to time constraints and difficulties returning values from model that aren't affected by duplicate col names
         * the decision was made to use existing perl script for now to generate statistics workbook
         * Perl script called from org.emmanet.utils.RunShell.java
         *///  w w  w. j ava 2s . co m
        RunShell rs = new RunShell();
        //TODO BEFORE GOING LIVE CHECK THAT THIS RUNS /INTERNAL/SCRIPTS/PERL/archive2excel.pl
        // AND ADD PATH AND SCRIPT IN PLACE OF BELOW AND UNCOMMENT //#####
        //String[] run = {"/home/phil/","string.pl"};
        //Hardcoded for now until this is rebuilt TODO
        String[] run = { "/data/web/internal/scripts/perl/",
                "archive2excel.pl -v -o statistics.xls -u phil.1 -p wilkinson -d emmastr" };
        //String[] run = {"/data/web/EmmaStrains/cron/","statistics.sh search strains emmastr"}; //not working either
        rs.execute(run);
        //#####httpServletResponse.sendRedirect("http://internal.emmanet.org/statistics/statistics.xls");
        httpServletResponse.sendRedirect("http://internal.emmanet.org/statistics/statistics.xls");

        columns = (List) map.get("columns_emmaStrains");
        data = (List) map.get("data_emmaStrains");
    }

    //SEND ARRAY OF NAMES TO CREATE SHEETS AND COUNT
    for (int i = 0; i < sheets.length; i++) {

        sheet = wb.createSheet(sheets[i]);
        // Create a row and put some cells in it. Rows are 0 based.
        for (int ii = 0; ii < data.size(); ii++) {

            HSSFRow row = sheet.createRow((short) ii);
            HSSFCell cell = null;
            //HEADER STYLE
            HSSFCellStyle style = wb.createCellStyle();
            style.setFillBackgroundColor(HSSFColor.AQUA.index);
            style.setFillForegroundColor(HSSFColor.WHITE.index);
            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

            for (int iii = 0; iii < columns.size(); iii++) {
                if (ii == 0) {
                    // first row for header col name
                    for (int cn = 0; cn < columns.size(); cn++) {
                        cell = row.createCell((short) cn);
                        cell.setCellValue((String) columns.get(cn));
                        //cell.setCellValue((HSSFRichTextString) columns.get(cn));

                        //cell.setCellStyle(style);
                        //System.out.println((String) columns.get(cn));
                    }

                } else {

                    for (int cn = 0; cn < columns.size(); cn++) {

                        cell = row.createCell((short) cn);//iii
                        String s = (String) columns.get(cn);
                        //TODO FOR TEST
                        //SET DAOs
                        if (filename.equals("stats")) {
                            //sd = (StrainsDAO) data.get(ii);
                            //columns = (List)map.get("columns_emmaStrains");
                            // TODO IF STATEMENTS TO GET DATA AND SET CELL CONTENTS
                            //cell.setCellValue((String)data.get(ii).toString());

                            //cell.setCellValue((String)data.get(ii).toString());
                            //TODO CURRENTLY ITERATING OVER LIST RESULTS THEN ITERATING AGAIN OVER OBJECT
                            // NEED TO REMOVE OR REPOSITION OBJECT ITERATOR it line 68
                            //#Iterator it = data.iterator();
                            //#while (it.hasNext()) {
                            // /*while (ii < data.length) {
                            ////  Object[] dataVal = (Object[])data.get(ii);
                            // *do rest here
                            // }
                            // */
                            //# Object[] dataVal = (Object[]) it.next();
                            //System.out.println(ii + " +=+=+ ");
                            //cell.setCellValue(dataVal[0].toString());
                            //System.out.println(dataVal[0]);
                            //System.out.println(dataVal[1]);
                            //cell.setCellValue(dataVal[1].toString());
                            //System.out.println(dataVal[2]);
                            // cell.setCellValue(dataVal[2].toString());
                            //System.out.println(dataVal[3]);
                            // cell.setCellValue(dataVal[3].toString());
                            // System.out.println(dataVal[4]);
                            // cell.setCellValue(dataVal[4].toString());

                            //// if (s.equals("Muttype")) cell.setCellValue(dataVal[0].toString());
                            //if (s.equals("subtype")) cell.setCellValue(dataVal[1].toString());
                            //System.out.println(dataVal[1]);
                            //// if (s.equals("EMMA ID")) cell.setCellValue(dataVal[2].toString());
                            //System.out.println(dataVal[2].toString());
                            //// if (s.equals("name")) cell.setCellValue(dataVal[3].toString());
                            //// if (s.equals("gene")) cell.setCellValue(dataVal[4].toString());
                            //# }

                            //cell.setCellValue(dataVal.toString());
                            // System.out.println(dataVal[0]);
                            // returnedOut.put("LabServiceTimeToArch" + i, laboServiceTimes[0]);
                            // cell.setCellValue( (HSSFRichTextString) data.get(ii));

                        } else {
                            sd = (StrainsDAO) data.get(ii);
                            // }

                            //TODO //TODO FOR TEST END

                            if (s.equals("id_str"))
                                cell.setCellValue(sd.getId_str());
                            if (s.equals("code_internal"))
                                cell.setCellValue(sd.getCode_internal());
                            if (s.equals("name"))
                                cell.setCellValue(sd.getName());
                            if (s.equals("health_status"))
                                cell.setCellValue(sd.getHealth_status());
                            if (s.equals("generation"))
                                cell.setCellValue(sd.getGeneration());
                            if (s.equals("maintenance"))
                                cell.setCellValue(sd.getMaintenance());
                            if (s.equals("id_str"))
                                cell.setCellValue(sd.getCharact_gen());
                            if (s.equals("charact_gen"))
                                cell.setCellValue(sd.getStr_access());
                            if (s.equals("username"))
                                cell.setCellValue(sd.getUsername());
                            if (s.equals("last_change"))
                                cell.setCellValue(sd.getLast_change());
                            if (s.equals("pheno_text"))
                                cell.setCellValue(sd.getPheno_text());
                            if (s.equals("per_id_per"))
                                cell.setCellValue(sd.getPer_id_per());
                            if (s.equals("per_id_per_contact"))
                                cell.setCellValue(sd.getPer_id_per_contact());
                            if (s.equals("emma_id"))
                                cell.setCellValue(sd.getEmma_id());
                            if (s.equals("mgi_ref"))
                                cell.setCellValue(sd.getMgi_ref());
                            if (s.equals("str_type"))
                                cell.setCellValue(sd.getStr_type());
                            if (s.equals("mta_file"))
                                cell.setCellValue(sd.getMta_file());
                            if (s.equals("gp_release"))
                                cell.setCellValue(sd.getGp_release());
                            if (s.equals("name_status"))
                                cell.setCellValue(sd.getName_status());
                            if (s.equals("date_published"))
                                cell.setCellValue(sd.getDate_published());
                            if (s.equals("str_status"))
                                cell.setCellValue(sd.getStr_status());
                            if (s.equals("res_id"))
                                cell.setCellValue(sd.getRes_id());
                            if (s.equals("require_homozygous"))
                                cell.setCellValue(sd.getRequire_homozygous());
                            if (s.equals("archive_id"))
                                cell.setCellValue(sd.getArchive_id());
                            if (s.equals("bg_id_bg"))
                                cell.setCellValue(sd.getBg_id_bg());
                        }
                    }
                }
            }
        }
        //AUTOSIZE ACCORDING TO LIST LENGTH AT END OF DATA
        for (i = 0; i < columns.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }

        // Freeze just one row, 1st row usually field names
        if (freeze == 1) {
            // freeze row
            sheet.createFreezePane(0, 1, 0, 1);
        }
    }

}

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();/* w  ww .  ja v a2 s.  c  o  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  w w w.j a  v  a2 s  .  c om*/
    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;
}

From source file:org.forzaframework.util.XlsUtils.java

License:Apache License

public static HSSFCellStyle getDefaultHeaderCellStyle(HSSFWorkbook wb, Boolean defaultFormat) {
    HSSFCellStyle headerCellStyle = null;
    if (defaultFormat != null && defaultFormat) {
        //Le damos formato a los encabezados
        headerCellStyle = wb.createCellStyle();
        headerCellStyle.setBorderBottom(BorderStyle.DOTTED);
        headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //        headerCellStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
        headerCellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
        //Creamos el tipo de fuente
        HSSFFont headerFont = wb.createFont();
        //            headerFont.setFontName(HSSFFont.FONT_ARIAL);
        headerFont.setBold(Boolean.TRUE);
        headerFont.setColor(HSSFFont.COLOR_NORMAL);
        headerFont.setFontHeightInPoints((short) 8);
        headerCellStyle.setFont(headerFont);
    }/*from   w ww  .  ja va  2  s  . c  o  m*/
    return headerCellStyle;
}

From source file:org.gbif.portal.web.download.ExcelFileWriter.java

License:Open Source License

/**
 * Write out the delimited file./* www.j  a  v  a 2  s.co m*/
 * 
 * @throws IOException 
 */
public void writeFile() throws Exception {

    //Create FieldFormatter - the object that is i18n aware
    FieldFormatter ff = new FieldFormatter(downloadFields, messageSource, locale, hostUrl);

    //stick requested fields into list of strings
    List<String> requestedFieldNames = new ArrayList<String>();
    for (Field field : downloadFields)
        requestedFieldNames.add(field.getFieldName());

    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet(messageSource.getMessage(sheetName, null, sheetName, locale));

    //create a titles style
    HSSFCellStyle titlesStyle = workbook.createCellStyle();
    titlesStyle.setFillPattern((short) HSSFCellStyle.SOLID_FOREGROUND);
    titlesStyle.setFillBackgroundColor(HSSFColor.DARK_GREEN.index);
    HSSFFont font = workbook.createFont();
    font.setColor(HSSFColor.WHITE.index);
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    titlesStyle.setFont(font);

    //write out the field headings
    for (int i = 0; i < downloadFields.size(); i++) {
        Field field = downloadFields.get(i);
        HSSFCell cell = getCell(sheet, 0, i);
        cell.setCellStyle(titlesStyle);
        setText(cell, messageSource.getMessage(field.getFieldI18nNameKey(), null, field.getFieldI18nNameKey(),
                locale));
    }

    //Create Results outputter - the object that knows about the required format
    ResultsOutputter resultsOutputter = new ExcelResultsOutputter(workbook, sheet, downloadFieldMappings,
            requestedFieldNames, ff);

    //check for citation
    if (addCitation && zipped) {
        DataResourceAuditor cro = new DataResourceAuditor();
        cro.setNextResultsOutputter(resultsOutputter);
        resultsOutputter = cro;
    }

    //pass both to the query manager
    outputProcess.process(resultsOutputter);

    //write out the workbook
    workbook.write(outputStream);
    outputStream.flush();

    //close the file stream
    if (zipped)
        ((ZipOutputStream) outputStream).closeEntry();

    //write out the citation
    if (addCitation && zipped) {
        downloadUtils.outputCitation(outputStream, (DataResourceAuditor) resultsOutputter, citationFileName,
                locale, hostUrl);
    }

    //write out the rights
    if (addRights && zipped) {
        downloadUtils.outputRights(outputStream, (DataResourceAuditor) resultsOutputter, rightsFileName, locale,
                hostUrl);
    }

    //log usage
    if (logEventId != null && resultsOutputter instanceof DataResourceAuditor) {
        downloadUtils.logDownloadUsage((DataResourceAuditor) resultsOutputter, logEventId);
    }

    //run secondary outputs
    if (zipped && secondaryDownloadOutputs != null) {
        downloadUtils.addSecondaryOutputs((ZipOutputStream) outputStream, secondaryDownloadOutputs);
    }

    //once returned rename the file to indicate the file has been written
    signalFileWriteComplete();
}

From source file:org.gbif.portal.web.view.ExcelView.java

License:Open Source License

/**
 * @see org.springframework.web.servlet.view.document.AbstractExcelView#buildExcelDocument(java.util.Map, org.apache.poi.hssf.usermodel.HSSFWorkbook, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from w  ww .  ja v  a 2s .co  m
@SuppressWarnings("unchecked")
protected void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest request,
        HttpServletResponse response) {

    Locale locale = RequestContextUtils.getLocale(request);

    //create results sheet
    String sheetTitle = messageSource.getMessage(resultsSheetTitleI18nKey, null, locale);
    HSSFSheet resultsSheet = workbook.createSheet(sheetTitle);
    resultsSheet.setDefaultColumnWidth((short) (defaultColumnWidth));

    //create a titles style
    HSSFCellStyle titlesStyle = workbook.createCellStyle();
    titlesStyle.setFillPattern((short) HSSFCellStyle.SOLID_FOREGROUND);
    titlesStyle.setFillBackgroundColor(HSSFColor.DARK_GREEN.index);
    HSSFFont font = workbook.createFont();
    font.setColor(HSSFColor.WHITE.index);
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    titlesStyle.setFont(font);

    //create a hyperlink style
    HSSFCellStyle hyperlinkStyle = workbook.createCellStyle();
    HSSFFont hyperLinkFont = workbook.createFont();
    hyperLinkFont.setColor(HSSFColor.BLUE.index);
    hyperlinkStyle.setFont(hyperLinkFont);

    //reused cell reference
    HSSFCell cell = null;

    //write results sheet
    List<Field> fields = (List<Field>) request.getAttribute("requestedFields");
    List results = (List) request.getAttribute("results");

    int currentRow = 0;

    //column headings
    for (int i = 0; i < fields.size(); i++) {
        cell = getCell(resultsSheet, currentRow, i);
        cell.setCellStyle(titlesStyle);
        String title = messageSource.getMessage(fields.get(i).getFieldI18nNameKey(), null, locale);
        setText(cell, title);
        short titleLength = (short) (title.length() * charWidth);
        short columnWidth = resultsSheet.getColumnWidth((short) i);
        //update column width for long columns
        if (columnWidth < titleLength) {
            resultsSheet.setColumnWidth((short) i, (short) (titleLength));
        }
    }

    currentRow++;
    //results
    for (int i = 0; i < results.size(); i++) {

        Object result = results.get(i);

        for (int j = 0; j < fields.size(); j++) {

            Field field = fields.get(j);
            cell = getCell(resultsSheet, currentRow, j);

            try {
                short textWidth = defaultColumnWidth;
                String propertyValue = field.getRenderValue(request, messageSource, locale, result);
                if (propertyValue != null)
                    setText(cell, propertyValue);
                if (field instanceof UrlField) {
                    if (propertyValue != null && propertyValue.length() < urlMaxLength) {
                        String linkFormula = "HYPERLINK(\"" + propertyValue + "\")";
                        cell.setCellFormula(linkFormula);
                        cell.setCellStyle(hyperlinkStyle);
                    }
                }
                if (propertyValue != null) {

                    int textWidthInt = propertyValue.length() * charWidth;
                    if (textWidthInt > 32768) {
                        textWidth = Short.MAX_VALUE;
                    } else {
                        textWidth = (short) textWidthInt;
                    }
                }

                //update column width for long columns
                short columnWidth = resultsSheet.getColumnWidth((short) j);

                if (textWidth > columnWidth) {
                    resultsSheet.setColumnWidth((short) j, (short) textWidth);
                }
            } catch (Exception e) {
                logger.warn(e.getMessage(), e);
            }
        }
        currentRow++;
    }

    //set up details sheet
    HSSFSheet detailsSheet = workbook
            .createSheet(messageSource.getMessage(detailsSheetTitleI18nKey, null, locale));
    detailsSheet.setColumnWidth((short) 0, (short) 6000);
    detailsSheet.setColumnWidth((short) 1, (short) Short.MAX_VALUE);
    ;
    List<FilterDTO> filters = (List) request.getAttribute("filters");
    CriteriaDTO criteria = (CriteriaDTO) request.getAttribute("criteria");
    String query = FilterUtils.getQueryDescription(filters, criteria, messageSource, locale);
    cell = getCell(detailsSheet, 0, 0);
    cell.setCellStyle(titlesStyle);
    setText(cell, messageSource.getMessage("occurrence.search.description", null, locale));
    cell = getCell(detailsSheet, 0, 1);
    setText(cell, query);
    //add url for search
    cell = getCell(detailsSheet, 1, 0);
    cell.setCellStyle(titlesStyle);
    setText(cell, messageSource.getMessage("occurrence.search.url", null, locale));
    cell = getCell(detailsSheet, 1, 1);
    cell.setCellStyle(hyperlinkStyle);
    String url = "http://" + request.getHeader("host") + request.getContextPath() + "/occurrences/search.htm?"
            + CriteriaUtil.getUrl(criteria);
    setText(cell, url);
    //there is a formula limit in Excel of 255 characters
    if (url != null && url.length() < urlMaxLength) {
        String link = "HYPERLINK(\"" + url + "\")";
        cell.setCellFormula(link);
    }
    //add url for download page
    cell = getCell(detailsSheet, 2, 0);
    cell.setCellStyle(titlesStyle);
    setText(cell, messageSource.getMessage("occurrence.search.download.url", null, locale));
    cell = getCell(detailsSheet, 2, 1);
    cell.setCellStyle(hyperlinkStyle);
    String downloadurl = "http://" + request.getHeader("host") + request.getContextPath()
            + "/occurrences/download.htm?" + CriteriaUtil.getUrl(criteria);
    setText(cell, downloadurl);
    if (downloadurl != null && downloadurl.length() < urlMaxLength) {
        String link = "HYPERLINK(\"" + downloadurl + "\")";
        cell.setCellFormula(link);
    }
    //add date for this download
    cell = getCell(detailsSheet, 3, 0);
    cell.setCellStyle(titlesStyle);
    setText(cell, messageSource.getMessage("occurrence.search.download.date", null, locale));
    cell = getCell(detailsSheet, 3, 1);
    SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
    setText(cell, sdf.format(new Date(System.currentTimeMillis())));
}

From source file:org.ism.view.TableView.java

/**
 * ************************************************************************
 * Gestion des document au format XLS/*from   www . j a v a  2s.  c o m*/
 *
 * @param document
 * ***********************************************************************
 */
public void handlePostProcessXLS(Object document) {
    HSSFWorkbook wb = (HSSFWorkbook) document;
    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow header = sheet.getRow(0);
    HSSFCellStyle cellStyle = wb.createCellStyle();
    cellStyle.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
        header.getCell(i).setCellStyle(cellStyle);
        sheet.autoSizeColumn(i);
    }
}