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

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

Introduction

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

Prototype

public void setFont(HSSFFont font) 

Source Link

Usage

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 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;
}

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

License:Apache License

static public void modelToExcelSheet(HSSFWorkbook wb, String sheetName, List<Map<String, Object>> headers,
        List<Map<String, Object>> data, List<Map<String, Object>> footers, Integer freezePane,
        Boolean defaultFormat, Boolean createNewSheet, Integer indexSheet, Integer startInRow,
        Boolean printHeader, Boolean autoSizeColumns) {
    HSSFSheet sheet = getSheet(wb, sheetName, createNewSheet, indexSheet);
    HSSFCellStyle headerCellStyle = getDefaultHeaderCellStyle(wb, defaultFormat);
    HSSFCellStyle titlesCellStyle = null;
    if (defaultFormat != null && defaultFormat) {
        titlesCellStyle = wb.createCellStyle();
        //Creamos el tipo de fuente
        HSSFFont titleFont = wb.createFont();
        //            headerFont.setFontName(HSSFFont.FONT_ARIAL);
        titleFont.setBold(Boolean.TRUE);
        titleFont.setColor(HSSFFont.COLOR_NORMAL);
        titleFont.setFontHeightInPoints((short) 8);
        titlesCellStyle.setFont(titleFont);
    }//from  w w w.j  a  va 2 s  .c o m

    Integer col = 0;
    Integer row = 0;
    if (startInRow != null) {
        row = startInRow;
    }
    Map<Integer, Integer> columnWidthMap = new HashMap<Integer, Integer>();
    //Indice de la fila donde empieza los encabezados de titulo de cada columna
    Integer principalHeaderIndex = headers.size() - 1;
    if (printHeader != null && printHeader) {
        //Armamos el encabezado
        for (Map<String, Object> header : headers) {
            for (Map.Entry<String, Object> entry : header.entrySet()) {
                HSSFCell cell = getCell(sheet, row, col);
                if (defaultFormat != null && defaultFormat) {
                    if (principalHeaderIndex.equals(row)) {
                        //Colocamos el formato de la celda
                        cell.setCellStyle(headerCellStyle);
                    } else {
                        cell.setCellStyle(titlesCellStyle);
                    }
                }
                setValue(cell, entry.getValue());
                //Especificamos el ancho que tendra la columna
                if (autoSizeColumns != null && autoSizeColumns) {
                    columnWidthMap.put(col, entry.getValue().toString().length());
                }
                col++;
            }
            row++;
            col = 0;
        }
        //Ponemos la altura del encabezado
        setRowHeight(sheet, row - 1, (short) 420);
    }

    HSSFCellStyle detailCellStyle = getDefaultDetailCellStyle(wb, defaultFormat);

    Map<String, Object> principalHeader = headers.get(principalHeaderIndex);
    // datos
    for (Map<String, Object> map : data) {
        for (Map.Entry<String, Object> entry : principalHeader.entrySet()) {
            Object value = map.get(entry.getKey());
            buildCellAndCalculateColumnWidth(sheet, value, col, row, detailCellStyle, columnWidthMap,
                    autoSizeColumns);
            col++;
        }
        col = 0;
        row++;
    }
    HSSFCellStyle totalCellStyle = null;
    if (defaultFormat != null && defaultFormat) {
        //Armamos el formato los totales
        totalCellStyle = wb.createCellStyle();
        HSSFFont totalFont = wb.createFont();
        totalFont.setBold(Boolean.TRUE);
        totalFont.setColor(HSSFFont.COLOR_NORMAL);
        totalFont.setFontHeightInPoints((short) 8);
        totalCellStyle.setFont(totalFont);
    }

    if (footers != null) {
        for (Map<String, Object> footer : footers) {
            for (Map.Entry<String, Object> entry : principalHeader.entrySet()) {
                HSSFCell cell = getCell(sheet, row, col++);
                if (totalCellStyle != null) {
                    //Colocamos el formato de la celda
                    cell.setCellStyle(totalCellStyle);
                }

                Object object = footer.get(entry.getKey());
                if (object != null) {
                    setValue(cell, object);
                } else {
                    setText(cell, "");
                }
            }
        }
    }

    if (autoSizeColumns != null && autoSizeColumns) {
        setColumnsWidth(sheet, columnWidthMap, principalHeader.size());
    }

    if (freezePane != null && freezePane > 0) {
        //Colocamos la columna estatica y las filas del encabezado estaticas
        sheet.createFreezePane(freezePane, headers.size());
    }
}

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

License:Apache License

public static HSSFCellStyle getDefaultDetailCellStyle(HSSFWorkbook wb, Boolean defaultFormat) {
    HSSFCellStyle detailCellStyle = null;
    if (defaultFormat != null && defaultFormat) {
        //Armamos el formato para los datos del detalle
        detailCellStyle = wb.createCellStyle();
        HSSFFont detailFont = wb.createFont();
        detailFont.setFontHeightInPoints((short) 8);
        detailCellStyle.setFont(detailFont);
    }//from w w w. j  a  va  2s  .c om
    return detailCellStyle;
}

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  ww  w . j  a  v a2 s .  c  om*/
    return headerCellStyle;
}

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

License:Open Source License

/**
 * Write out the delimited file./*from w ww  .j a  v  a 2  s  .c  o 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  w w  . j a  va 2  s  . c o 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.goobi.production.flow.helper.SearchResultHelper.java

License:Open Source License

@SuppressWarnings("deprecation")
public HSSFWorkbook getResult(List<SearchColumn> columnList, String filter, String order,
        boolean showClosedProcesses, boolean showArchivedProjects) {
    List<SearchColumn> sortedList = new ArrayList<>(columnList.size());
    for (SearchColumn sc : columnList) {
        if (!sc.getTableName().startsWith("metadata")) {
            sortedList.add(sc);//from   w ww .ja  va2  s .com
        }
    }
    for (SearchColumn sc : columnList) {
        if (sc.getTableName().startsWith("metadata")) {
            sortedList.add(sc);
        }
    }
    columnList = sortedList;

    @SuppressWarnings("rawtypes")
    List list = search(columnList, filter, order, showClosedProcesses, showArchivedProjects);

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("Search results");

    // create title row
    int titleColumnNumber = 0;
    HSSFRow title = sheet.createRow(0);
    int columnNumber = 0;
    for (SearchColumn sc : columnList) {
        HSSFCell titleCell = title.createCell(titleColumnNumber++);
        titleCell.setCellValue(Helper.getTranslation(sc.getValue()));
        HSSFCellStyle cellStyle = wb.createCellStyle();
        HSSFFont cellFont = wb.createFont();
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        cellStyle.setFont(cellFont);
        titleCell.setCellStyle(cellStyle);
    }

    int rowNumber = 1;
    for (Object obj : list) {
        Object[] objArr = (Object[]) obj;
        HSSFRow row = sheet.createRow(rowNumber++);
        columnNumber = 0;
        for (Object entry : objArr) {
            HSSFCell cell = row.createCell(columnNumber++);
            if (entry != null) {
                cell.setCellValue(((String) entry).replace("\"", ""));
            } else {
                cell.setCellValue("");
            }
        }
    }

    sheet.createFreezePane(0, 1);
    for (int i = 0; i < columnList.size(); i++) {
        sheet.autoSizeColumn(i);
        if (sheet.getColumnWidth(i) > 15000) {
            sheet.setColumnWidth(i, 15000);
        }
    }

    return wb;
}

From source file:org.ivan.service.ExcelExporter.java

public <T extends Object> File createExcel(List<T> objects, String fileName, String sheetName) {

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

    HSSFFont font = workbook.createFont();
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    HSSFCellStyle style = workbook.createCellStyle();
    style.setFont(font);

    int cellNum = 0;
    int rowNum = 0;
    List<String> headers = getHeadersFromGetMethods(objects.get(0));
    Row row = sheet.createRow(rowNum++);
    for (int i = 0; i < headers.size(); i++) {
        String cup = headers.get(i);
        Cell cell = row.createCell(cellNum++);
        cell.setCellValue(cup);//from   w w w  . j av a  2s.  c o m
        cell.setCellStyle(style);
    }
    for (T obj : objects) {

        cellNum = 0;
        List<String> parameters = getValuesRecursive(obj);
        row = sheet.createRow(rowNum++);
        for (String parameter : parameters) {

            Cell cell = row.createCell(cellNum++);
            cell.setCellValue(parameter);
            sheet.autoSizeColumn(cellNum);
        }

    }

    try {
        FileOutputStream out = new FileOutputStream(new File(fileName));
        workbook.write(out);
        out.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.ivan.service.ExcelExporter.java

public <T extends Object, E extends Object> File createExcelFromMap(Map<T, List<E>> objects, String fileName) {

    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFFont font = workbook.createFont();
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    HSSFCellStyle style = workbook.createCellStyle();
    style.setFont(font);
    for (T mapKey : objects.keySet()) {

        HSSFSheet sheet = workbook.createSheet(mapKey.toString());
        int cellNum = 0;
        int rowNum = 0;
        List<String> headers = getHeadersFromGetMethods(objects.get(mapKey).get(0));

        Row row = sheet.createRow(rowNum++);
        for (int i = 0; i < headers.size(); i++) {
            String cup = headers.get(i);
            Cell cell = row.createCell(cellNum++);
            cell.setCellValue(cup);/*from w  ww .  j  av a 2s  .co  m*/
            cell.setCellStyle(style);
        }

        for (E object : objects.get(mapKey)) {
            cellNum = 0;
            List<String> parameters = getValuesRecursive(object);
            row = sheet.createRow(rowNum++);
            for (String parameter : parameters) {

                Cell cell = row.createCell(cellNum++);
                cell.setCellValue(parameter);
                sheet.autoSizeColumn(cellNum);
            }
        }
    }

    File file = new File(fileName + ".xls");
    try {
        FileOutputStream out = new FileOutputStream(file);
        workbook.write(out);
        out.close();

    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }

    return null;
}

From source file:org.jxstar.report.studio.ExportXlsBO.java

/**
 * ?/* w  w w. j  a  v  a  2 s  . c  o m*/
 * @param wb -- ?
 * @return
 */
public HSSFCellStyle createTitleStyle(HSSFWorkbook wb) {
    //
    HSSFFont cellFont = wb.createFont();
    cellFont.setFontName("");
    cellFont.setFontHeightInPoints((short) 16);
    cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

    //?
    HSSFCellStyle cellStyle = wb.createCellStyle();
    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
    cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    cellStyle.setFont(cellFont);

    return cellStyle;
}