Example usage for org.apache.poi.ss.usermodel Font getFontName

List of usage examples for org.apache.poi.ss.usermodel Font getFontName

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Font getFontName.

Prototype


String getFontName();

Source Link

Document

get the name for the font (i.e.

Usage

From source file:org.pentaho.di.trans.steps.excelwriter.ExcelWriterStep.java

License:Apache License

void writeField(Object v, ValueMetaInterface vMeta, ExcelWriterStepField excelField, Row xlsRow, int posX,
        Object[] row, int fieldNr, boolean isTitle) throws KettleException {
    try {//from  w  w  w .  j a  va 2s. co m
        boolean cellExisted = true;
        // get the cell
        Cell cell = xlsRow.getCell(posX);
        if (cell == null) {
            cellExisted = false;
            cell = xlsRow.createCell(posX);
        }

        // if cell existed and existing cell's styles should not be changed, don't
        if (!(cellExisted && meta.isLeaveExistingStylesUnchanged())) {

            // if the style of this field is cached, reuse it
            if (!isTitle && data.getCachedStyle(fieldNr) != null) {
                cell.setCellStyle(data.getCachedStyle(fieldNr));
            } else {
                // apply style if requested
                if (excelField != null) {

                    // determine correct cell for title or data rows
                    String styleRef = null;
                    if (!isTitle && !Utils.isEmpty(excelField.getStyleCell())) {
                        styleRef = excelField.getStyleCell();
                    } else if (isTitle && !Utils.isEmpty(excelField.getTitleStyleCell())) {
                        styleRef = excelField.getTitleStyleCell();
                    }

                    if (styleRef != null) {
                        Cell styleCell = getCellFromReference(styleRef);
                        if (styleCell != null && cell != styleCell) {
                            cell.setCellStyle(styleCell.getCellStyle());
                        }
                    }
                }

                // set cell format as specified, specific format overrides cell specification
                if (!isTitle && excelField != null && !Utils.isEmpty(excelField.getFormat())
                        && !excelField.getFormat().startsWith("Image")) {
                    setDataFormat(excelField.getFormat(), cell);
                }
                // cache it for later runs
                if (!isTitle) {
                    data.cacheStyle(fieldNr, cell.getCellStyle());
                }
            }
        }

        // create link on cell if requested
        if (!isTitle && excelField != null && data.linkfieldnrs[fieldNr] >= 0) {
            String link = data.inputRowMeta.getValueMeta(data.linkfieldnrs[fieldNr])
                    .getString(row[data.linkfieldnrs[fieldNr]]);
            if (!Utils.isEmpty(link)) {
                CreationHelper ch = data.wb.getCreationHelper();
                // set the link on the cell depending on link type
                Hyperlink hyperLink = null;
                if (link.startsWith("http:") || link.startsWith("https:") || link.startsWith("ftp:")) {
                    hyperLink = ch.createHyperlink(HyperlinkType.URL);
                    hyperLink.setLabel("URL Link");
                } else if (link.startsWith("mailto:")) {
                    hyperLink = ch.createHyperlink(HyperlinkType.EMAIL);
                    hyperLink.setLabel("Email Link");
                } else if (link.startsWith("'")) {
                    hyperLink = ch.createHyperlink(HyperlinkType.DOCUMENT);
                    hyperLink.setLabel("Link within this document");
                } else {
                    hyperLink = ch.createHyperlink(HyperlinkType.FILE);
                    hyperLink.setLabel("Link to a file");
                }

                hyperLink.setAddress(link);
                cell.setHyperlink(hyperLink);

                // if cell existed and existing cell's styles should not be changed, don't
                if (!(cellExisted && meta.isLeaveExistingStylesUnchanged())) {

                    if (data.getCachedLinkStyle(fieldNr) != null) {
                        cell.setCellStyle(data.getCachedLinkStyle(fieldNr));
                    } else {
                        // CellStyle style = cell.getCellStyle();
                        Font origFont = data.wb.getFontAt(cell.getCellStyle().getFontIndex());
                        Font hlink_font = data.wb.createFont();
                        // reporduce original font characteristics

                        hlink_font.setBold(origFont.getBold());
                        hlink_font.setCharSet(origFont.getCharSet());
                        hlink_font.setFontHeight(origFont.getFontHeight());
                        hlink_font.setFontName(origFont.getFontName());
                        hlink_font.setItalic(origFont.getItalic());
                        hlink_font.setStrikeout(origFont.getStrikeout());
                        hlink_font.setTypeOffset(origFont.getTypeOffset());
                        // make it blue and underlined
                        hlink_font.setUnderline(Font.U_SINGLE);
                        hlink_font.setColor(IndexedColors.BLUE.getIndex());
                        CellStyle style = cell.getCellStyle();
                        style.setFont(hlink_font);
                        cell.setCellStyle(style);
                        data.cacheLinkStyle(fieldNr, cell.getCellStyle());
                    }
                }
            }
        }

        // create comment on cell if requrested
        if (!isTitle && excelField != null && data.commentfieldnrs[fieldNr] >= 0
                && data.wb instanceof XSSFWorkbook) {
            String comment = data.inputRowMeta.getValueMeta(data.commentfieldnrs[fieldNr])
                    .getString(row[data.commentfieldnrs[fieldNr]]);
            if (!Utils.isEmpty(comment)) {
                String author = data.commentauthorfieldnrs[fieldNr] >= 0
                        ? data.inputRowMeta.getValueMeta(data.commentauthorfieldnrs[fieldNr]).getString(
                                row[data.commentauthorfieldnrs[fieldNr]])
                        : "Kettle PDI";
                cell.setCellComment(createCellComment(author, comment));
            }
        }
        // cell is getting a formula value or static content
        if (!isTitle && excelField != null && excelField.isFormula()) {
            // formula case
            cell.setCellFormula(vMeta.getString(v));
        } else {
            // static content case
            switch (vMeta.getType()) {
            case ValueMetaInterface.TYPE_DATE:
                if (v != null && vMeta.getDate(v) != null) {
                    cell.setCellValue(vMeta.getDate(v));
                }
                break;
            case ValueMetaInterface.TYPE_BOOLEAN:
                if (v != null) {
                    cell.setCellValue(vMeta.getBoolean(v));
                }
                break;
            case ValueMetaInterface.TYPE_STRING:
            case ValueMetaInterface.TYPE_BINARY:
                if (v != null) {
                    cell.setCellValue(vMeta.getString(v));
                }
                break;
            case ValueMetaInterface.TYPE_BIGNUMBER:
            case ValueMetaInterface.TYPE_NUMBER:
            case ValueMetaInterface.TYPE_INTEGER:
                if (v != null) {
                    cell.setCellValue(vMeta.getNumber(v));
                }
                break;
            default:
                break;
            }
        }
    } catch (Exception e) {
        logError("Error writing field (" + data.posX + "," + data.posY + ") : " + e.toString());
        logError(Const.getStackTracker(e));
        throw new KettleException(e);
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.table.xls.helper.HSSFFontWrapper.java

License:Open Source License

/**
 * Creates a HSSFFontWrapper for the excel font.
 *
 * @param font//  w  ww .  j a  v  a  2 s  .c o  m
 *          the font.
 */
public HSSFFontWrapper(final Font font) {
    if (font == null) {
        throw new NullPointerException("Font is null");
    }
    if (font.getColor() < 0) {
        throw new IllegalArgumentException("Negative color index is not allowed");
    }

    fontName = normalizeFontName(font.getFontName());
    fontHeight = font.getFontHeightInPoints();
    bold = font.getBold();
    italic = font.getItalic();
    underline = (font.getUnderline() != HSSFFont.U_NONE);
    strikethrough = font.getStrikeout();
    colorIndex = font.getColor();
}

From source file:ru.icc.cells.ssdc.DataLoader.java

License:Apache License

private void fillFont(CFont font, Font excelFont) {
    font.setName(excelFont.getFontName());

    // TODO    CFont font
    //font.setColor( excelFont.getColor() );

    font.setHeight(excelFont.getFontHeight());
    font.setHeightInPoints(excelFont.getFontHeightInPoints());

    // TODO ?  ? Boldweight, ?? ? ? 
    short boldWeight = excelFont.getBoldweight();
    if (boldWeight >= 700)
        font.setBold(true);//from www  .  j a v a  2s.  c  o  m

    font.setItalic(excelFont.getItalic());
    font.setStrikeout(excelFont.getStrikeout());

    byte underline = excelFont.getUnderline();
    if (underline != Font.U_NONE)
        font.setUnderline(true);
    if (underline == Font.U_DOUBLE || underline == Font.U_DOUBLE_ACCOUNTING)
        font.setDoubleUnderline(true);
}

From source file:ru.spb.nicetu.tableviewer.server.XlsToHtml.java

License:Apache License

private void fontStyle(CellStyle style, Formatter out, boolean isBuiltIn) {
    Font font = wb.getFontAt(style.getFontIndex());

    if (font.getBoldweight() >= HSSFFont.BOLDWEIGHT_BOLD)
        styleOut("font-weight", "bold", out, isBuiltIn);
    if (font.getItalic())
        styleOut("font-style", "italic", out, isBuiltIn);
    if (font.getFontName() != null && !"".equals(font.getFontName()))
        styleOut("font-family", font.getFontName(), out, isBuiltIn);

    int fontheight = font.getFontHeightInPoints();
    if (fontheight == 9) {
        //fix for stupid ol Windows
        fontheight = 10;//  www.  ja v a  2  s.c  o  m
    }
    styleOut("font-size", "" + fontheight + "pt", out, isBuiltIn);

    // Font color is handled with the other colors
}

From source file:uk.ac.liverpool.spreadsheet.ExcelFeatureAnalysis.java

License:Apache License

private static void analyseSpreadsheet(Element da, ExcelFeatureAnalysis efa) {

    Element s = new Element("spreadsheets", sn);
    da.addContent(s);//from w ww .  j  a  v  a  2  s . c  o m
    s.setAttribute("numberOfSheets", "" + efa.wb.getNumberOfSheets());
    // workbook wide features

    List<? extends PictureData> allPictures = efa.wb.getAllPictures();
    if (allPictures != null && allPictures.size() > 0) {
        Element oo = new Element("Pictures", sn);
        s.addContent(oo);
        for (PictureData pd : allPictures) {
            Element ob = new Element("Picture", sn);
            ob.setAttribute("mimeType", pd.getMimeType());
            oo.addContent(ob);
        }
    }

    int numfonts = efa.wb.getNumberOfFonts();
    if (numfonts > 0) {
        Element oo = new Element("Fonts", sn);
        s.addContent(oo);
        for (int i = 0; i < numfonts; i++) {
            Font cs = efa.wb.getFontAt((short) i);
            Element ob = new Element("Font", sn);
            ob.setAttribute("Name", cs.getFontName());

            ob.setAttribute("Charset", "" + cs.getCharSet());
            oo.addContent(ob);
        }
    }

    if (efa.hswb != null) {

        DocumentSummaryInformation dsi = efa.hswb.getDocumentSummaryInformation();
        if (dsi != null)
            s.setAttribute("OSVersion", "" + dsi.getOSVersion());
        // Property[] properties = dsi.getProperties();
        // CustomProperties customProperties = dsi.getCustomProperties();

        List<HSSFObjectData> eo = efa.hswb.getAllEmbeddedObjects();
        if (eo != null && eo.size() > 0) {
            Element oo = new Element("EmbeddedObjects", sn);
            s.addContent(oo);
            for (HSSFObjectData o : eo) {
                Element ob = new Element("EmbeddedObject", sn);
                ob.setAttribute("name", o.getOLE2ClassName());
                oo.addContent(ob);
            }

        }
    } else if (efa.xswb != null) {
        try {
            POIXMLProperties properties = efa.xswb.getProperties();
            List<PackagePart> allEmbedds = efa.xswb.getAllEmbedds();
            if (allEmbedds != null && allEmbedds.size() > 0) {
                Element oo = new Element("EmbeddedObjects", sn);
                s.addContent(oo);

                for (PackagePart p : allEmbedds) {
                    Element ob = new Element("EmbeddedObject", sn);
                    ob.setAttribute("mimeType", p.getContentType());
                    ob.setAttribute("name", p.getPartName().getName());

                    oo.addContent(ob);
                }
            }
        } catch (OpenXML4JException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    int nn = efa.wb.getNumberOfNames();
    if (nn > 0) {
        Element oo = new Element("NamedCells", sn);
        s.addContent(oo);
    }

    // sheet specific features
    int total = efa.wb.getNumberOfSheets();
    for (int c = 0; c < total; c++) {
        Sheet sheet = efa.wb.getSheetAt(c);
        Element single = new Element("sheet", sn);
        s.addContent(single);
        analyseSheet(sheet, single, sn, efa);
    }
}

From source file:uk.co.spudsoft.birt.emitters.excel.StyleManagerUtils.java

License:Open Source License

/**
 * Add font details to an AttributedString.
 * @param attrString//from   ww w . j av  a 2  s .  c o m
 * The AttributedString to modify.
 * @param font
 * The font to take attributes from.
 * @param startIdx
 * The index of the first character to be attributed (inclusive).
 * @param endIdx
 * The index of the last character to be attributed (inclusive). 
 */
protected void addFontAttributes(AttributedString attrString, Font font, int startIdx, int endIdx) {
    attrString.addAttribute(TextAttribute.FAMILY, font.getFontName(), startIdx, endIdx);
    attrString.addAttribute(TextAttribute.SIZE, (float) font.getFontHeightInPoints(), startIdx, endIdx);
    if (font.getBoldweight() == Font.BOLDWEIGHT_BOLD)
        attrString.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, startIdx, endIdx);
    if (font.getItalic())
        attrString.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, startIdx, endIdx);
    if (font.getUnderline() == Font.U_SINGLE)
        attrString.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, startIdx, endIdx);
}

From source file:uk.co.spudsoft.birt.emitters.excel.StyleManagerUtils.java

License:Open Source License

/**
 * Calculate the height of a string formatted according to a set of RichTextRuns and fitted within a give width.
 * @param sourceText//from   w ww .  j a v a  2s . c  o m
 * The string to be measured.
 * @param defaultFont
 * The font to be used prior to the first RichTextRun.
 * @param widthMM
 * The width of the output.
 * @param richTextRuns
 * The list of RichTextRuns to be applied to the string
 * @return
 * The heigh, in points, of a box big enough to contain the formatted sourceText.
 */
public float calculateTextHeightPoints(String sourceText, Font defaultFont, double widthMM,
        List<RichTextRun> richTextRuns) {
    log.debug("Calculating height for ", sourceText);

    final float widthPt = (float) (72 * Math.max(0, widthMM - 6) / 25.4);

    float totalHeight = 0;
    String[] textLines = sourceText.split("\n");
    int lineStartIndex = 0;
    String lastLine = null;
    Font font = defaultFont;
    for (String textLine : textLines) {
        if (lastLine != null) {
            lineStartIndex += lastLine.length() + 1;
        }
        lastLine = textLine;

        AttributedString attrString = new AttributedString(textLine.isEmpty() ? " " : textLine);
        int runEnd = textLine.length();

        int richTextRunIndex = getRichTextRunIndexForStart(richTextRuns, lineStartIndex);
        if (richTextRunIndex >= 0) {
            font = richTextRuns.get(richTextRunIndex).font;
            if ((richTextRunIndex < richTextRuns.size() - 1)
                    && (richTextRuns.get(richTextRunIndex + 1).startIndex < runEnd)) {
                runEnd = richTextRuns.get(richTextRunIndex + 1).startIndex;
            }
        }

        log.debug("Adding attribute - [", 0, " - ", runEnd, "] = ", defaultFont.getFontName(), " ",
                defaultFont.getFontHeightInPoints(), "pt");
        addFontAttributes(attrString, font, 0, textLine.isEmpty() ? 1 : runEnd);

        for (++richTextRunIndex; (richTextRunIndex < richTextRuns.size())
                && (richTextRuns.get(richTextRunIndex).startIndex < lineStartIndex
                        + textLine.length()); ++richTextRunIndex) {
            RichTextRun run = richTextRuns.get(richTextRunIndex);
            RichTextRun nextRun = richTextRunIndex < richTextRuns.size() - 1
                    ? richTextRuns.get(richTextRunIndex + 1)
                    : null;
            if ((run.startIndex >= lineStartIndex)
                    && (run.startIndex < lineStartIndex + textLine.length() + 1)) {
                int startIdx = run.startIndex - lineStartIndex;
                int endIdx = (nextRun == null ? sourceText.length() : nextRun.startIndex) - lineStartIndex;
                if (endIdx > textLine.length()) {
                    endIdx = textLine.length();
                }
                if (startIdx < endIdx) {
                    log.debug("Adding attribute: [", startIdx, " - ", endIdx, "] = ", run.font.getFontName(),
                            " ", run.font.getFontHeightInPoints(), "pt");
                    addFontAttributes(attrString, run.font, startIdx, endIdx);
                }
            }
        }

        LineBreakMeasurer measurer = new LineBreakMeasurer(attrString.getIterator(), frc);

        float heightAdjustment = 0.0F;
        int lineLength = textLine.isEmpty() ? 1 : textLine.length();
        while (measurer.getPosition() < lineLength) {
            TextLayout layout = measurer.nextLayout(widthPt);
            float lineHeight = layout.getAscent() + layout.getDescent() + layout.getLeading();
            if (layout.getDescent() + layout.getLeading() > heightAdjustment) {
                heightAdjustment = layout.getDescent() + layout.getLeading();
            }
            log.debug("Line: ", textLine, " gives height ", lineHeight, "(", layout.getAscent(), "/",
                    layout.getDescent(), "/", layout.getLeading(), ")");
            totalHeight += lineHeight;
        }
        totalHeight += heightAdjustment;

    }
    log.debug("Height calculated as ", totalHeight);
    return totalHeight;
}