Example usage for org.apache.poi.hssf.usermodel HSSFWorkbook createFont

List of usage examples for org.apache.poi.hssf.usermodel HSSFWorkbook createFont

Introduction

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

Prototype


@Override
public HSSFFont createFont() 

Source Link

Document

create a new Font and add it to the workbook's font table

Usage

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 ww  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.generationcp.breeding.manager.crossingmanager.util.CrossingManagerExporter.java

License:Open Source License

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

    // set cell style for labels in the description sheet
    CellStyle labelStyle = wb.createCellStyle();
    labelStyle.setFillForegroundColor(IndexedColors.BROWN.getIndex());
    labelStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    Font labelFont = wb.createFont();
    labelFont.setColor(IndexedColors.WHITE.getIndex());
    labelFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    labelStyle.setFont(labelFont);//from  ww w.  ja va 2s  .  c  o  m
    styles.put(LABEL_STYLE, labelStyle);

    // set cell style for headings related to Conditions/Factors
    CellStyle factorHeadingStyle = wb.createCellStyle();
    factorHeadingStyle.setFillForegroundColor(IndexedColors.SEA_GREEN.getIndex());
    factorHeadingStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    factorHeadingStyle.setAlignment(CellStyle.ALIGN_CENTER);
    Font factorHeadingfont = wb.createFont();
    factorHeadingfont.setColor(IndexedColors.WHITE.getIndex());
    factorHeadingfont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    factorHeadingStyle.setFont(factorHeadingfont);
    styles.put(FACTOR_HEADING_STYLE, factorHeadingStyle);

    // set cell style for headings related to Constants/Variates
    CellStyle variateHeadingStyle = wb.createCellStyle();
    variateHeadingStyle.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
    variateHeadingStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    variateHeadingStyle.setAlignment(CellStyle.ALIGN_CENTER);
    Font variateHeadingFont = wb.createFont();
    variateHeadingFont.setColor(IndexedColors.WHITE.getIndex());
    variateHeadingFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    variateHeadingStyle.setFont(variateHeadingFont);
    styles.put(VARIATE_HEADING_STYLE, variateHeadingStyle);

    //set cell style for numeric values (left alignment)
    CellStyle numericStyle = wb.createCellStyle();
    numericStyle.setAlignment(CellStyle.ALIGN_LEFT);
    styles.put(NUMERIC_STYLE, numericStyle);

    return styles;
}

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  w  w.ja  va  2s  .c  o m
        }
    }
    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.hsh.bfr.db.exports.ExcelExport.java

License:Open Source License

public void doExport(final String filename, final MyDBTable myDB, final JProgressBar progress,
        final boolean exportFulltext, final String zeilen2Do) {
    //filename = "C:/Users/Armin/Documents/private/freelance/BfR/Data/100716/Matrices_BLS-Liste.xls";
    Runnable runnable = new Runnable() {
        public void run() {
            try {
                if (progress != null) {
                    progress.setVisible(true);
                    progress.setStringPainted(true);
                    progress.setString("Exporting Excel Datei...");
                    progress.setMinimum(0);
                    progress.setMaximum(myDB.getRowCount());
                    progress.setValue(0);
                }/*  www  .j  a  v a  2s.  co  m*/

                HSSFWorkbook wb = new HSSFWorkbook();
                HSSFSheet sheet = wb.createSheet(myDB.getActualTable().getTablename());
                // Create Titel
                cs = wb.createCellStyle();
                cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                HSSFFont font = wb.createFont();
                font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                cs.setFont(font);
                HSSFRow row0 = sheet.createRow(0);
                //row0.setRowStyle(cs);
                colLfd = 0;
                for (int j = 0; j < myDB.getColumnCount(); j++) {
                    if (myDB.getColumn(j).isVisible()) {
                        HSSFCell cell = row0.createCell(colLfd);
                        colLfd++;
                        cell.setCellValue(myDB.getColumn(j).getColumnName());
                        cell.setCellStyle(cs);
                    }
                }
                //String[] mnTable = myDB.getActualTable().getMNTable();
                MyTable[] myFs = myDB.getActualTable().getForeignFields();
                for (int i = 1; i <= myDB.getRowCount(); i++) {
                    if (progress != null)
                        progress.setValue(i);
                    //System.out.println(myDB.getValueAt(i, 0) + "_" + myDB.isVisible());
                    HSSFRow rowi = sheet.createRow(i);
                    for (int j = 0; j < myDB.getColumnCount(); j++) {
                        Object res = null;
                        if (j > 0 && myFs != null && myFs.length > j - 1 && myFs[j - 1] != null
                                && myFs[j - 1].getTablename().equals("DoubleKennzahlen")) {
                            //if (j > 0 && mnTable != null && j-1 < mnTable.length && mnTable[j - 1] != null && mnTable[j - 1].equals("DBL")) {
                            getDblVal(myDB, i - 1, j, row0, rowi);
                            /*
                            getDblVal(myDB, i-1, j, "Einzelwert", row0, rowi);
                            getDblVal(myDB, i-1, j, "Wiederholungen", row0, rowi);
                            getDblVal(myDB, i-1, j, "Mittelwert", row0, rowi);
                            getDblVal(myDB, i-1, j, "Median", row0, rowi);
                            getDblVal(myDB, i-1, j, "Minimum", row0, rowi);
                            getDblVal(myDB, i-1, j, "Maximum", row0, rowi);
                            getDblVal(myDB, i-1, j, "Standardabweichung", row0, rowi);
                            getDblVal(myDB, i-1, j, "LCL95", row0, rowi);
                            getDblVal(myDB, i-1, j, "UCL95", row0, rowi);
                            getDblVal(myDB, i-1, j, "Verteilung", row0, rowi);
                            getDblVal(myDB, i-1, j, "Funktion (Zeit)", row0, rowi);
                            getDblVal(myDB, i-1, j, "Funktion (?)", row0, rowi);
                            getDblVal(myDB, i-1, j, "Undefiniert (n.d.)", row0, rowi);
                            */
                        } else {
                            if (exportFulltext) {
                                res = myDB.getVisibleCellContent(i - 1, j);
                            } else {
                                res = myDB.getValueAt(i - 1, j);
                            }
                            //MyLogger.handleMessage(res);
                            if (res != null)
                                rowi.createCell(j).setCellValue(res.toString());
                            else
                                rowi.createCell(j);
                        }
                    }
                }

                try {
                    FileOutputStream fileOut = new FileOutputStream(filename);
                    wb.write(fileOut);
                    fileOut.close();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(progress, e.getMessage(), "Export Problem",
                            JOptionPane.OK_OPTION);
                }

                if (progress != null) {
                    progress.setValue(myDB.getRowCount());
                    progress.setVisible(false);
                }
            } catch (Exception e) {
                MyLogger.handleException(e);
            }
        }
    };

    Thread thread = new Thread(runnable);
    thread.start();
}

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);//from   w w w.  java2  s .  c om

    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);
        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);/*  ww  w. j av  a 2 s  . co  m*/
    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);
            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

/**
 * ?/*from w  w  w .  ja  va2  s  .  com*/
 * @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;
}

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

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

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

    //
    cellStyle.setBorderBottom((short) 1);
    cellStyle.setBorderLeft((short) 1);
    cellStyle.setBorderRight((short) 1);
    cellStyle.setBorderTop((short) 1);

    return cellStyle;
}

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 createCellStyle(HSSFWorkbook wb) {
    //
    HSSFFont cellFont = wb.createFont();
    cellFont.setFontName("");
    cellFont.setFontHeightInPoints((short) 9);

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

    //
    cellStyle.setBorderBottom((short) 1);
    cellStyle.setBorderLeft((short) 1);
    cellStyle.setBorderRight((short) 1);
    cellStyle.setBorderTop((short) 1);

    return cellStyle;
}

From source file:org.metaeffekt.core.inventory.processor.writer.InventoryWriter.java

License:Apache License

private HSSFCellStyle createHeaderStyle(HSSFWorkbook myWorkBook) {
    Font headerFont = myWorkBook.createFont();
    headerFont.setColor(Font.COLOR_NORMAL);

    HSSFPalette palette = myWorkBook.getCustomPalette();
    HSSFColor headerColor = palette.findSimilarColor((byte) 149, (byte) 179, (byte) 215);

    HSSFCellStyle headerStyle = myWorkBook.createCellStyle();
    headerStyle.setFillForegroundColor(headerColor.getIndex());
    headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    headerStyle.setFont(headerFont);/*  w w w  .j a  v a2 s .co m*/
    headerStyle.setWrapText(true);
    return headerStyle;
}