/** * See the comment for the given cell * * @param cell * the cell * @param message * the comment message */ public static void setComment(HSSFCell cell, String message) { Drawing drawing = cell.getSheet().createDrawingPatriarch(); CreationHelper factory = cell.getSheet().getWorkbook().getCreationHelper(); // When the comment box is visible, have it show in a 1x3 space ClientAnchor anchor = factory.createClientAnchor(); anchor.setCol1(cell.getColumnIndex()); anchor.setCol2(cell.getColumnIndex() + 1); anchor.setRow1(cell.getRowIndex()); anchor.setRow2(cell.getRowIndex() + 1); anchor.setDx1(100); anchor.setDx2(1000); anchor.setDy1(100); anchor.setDy2(1000); // Create the comment and set the text+author Comment comment = drawing.createCellComment(anchor); RichTextString str = factory.createRichTextString(message); comment.setString(str); comment.setAuthor("TURNUS"); // Assign the comment to the cell cell.setCellComment(comment); }
@Override public Cell set(RichText s) { s = getWorkbook().cache(s); Object old = get(); RichTextString richText = getWorkbook().createRichTextString(s.toString()); for (Run run : s) { PoiFont font = getWorkbook().getPoiFont(getCellStyle().getFont(), run.getAttributes()); richText.applyFont(run.getStart(), run.getEnd(), font.getPoiFont()); } poiCell.setCellValue(richText); updateRow(); valueChanged(old, s); return this; }
private Comment createCellComment(String author, String comment) { // comments only supported for XLSX if (data.sheet instanceof XSSFSheet) { CreationHelper factory = data.wb.getCreationHelper(); Drawing drawing = data.sheet.createDrawingPatriarch(); ClientAnchor anchor = factory.createClientAnchor(); Comment cmt = drawing.createCellComment(anchor); RichTextString str = factory.createRichTextString(comment); cmt.setString(str); cmt.setAuthor(author); return cmt; } return null; }
/** * Validates the attributes for this <code>Tag</code>. This tag must have a * body. */ @SuppressWarnings("unchecked") public void validateAttributes() throws TagParseException { super.validateAttributes(); if (isBodiless()) throw new TagParseException("Group tags must have a body."); TagContext context = getContext(); Map<String, Object> beans = context.getBeans(); Map<String, RichTextString> attributes = getAttributes(); String groupDir = AttributeUtil.evaluateStringSpecificValues(attributes.get(ATTR_GROUP_DIR), beans, ATTR_GROUP_DIR, Arrays.asList(GROUP_DIR_ROWS, GROUP_DIR_COLS, GROUP_DIR_NONE), GROUP_DIR_ROWS); if (GROUP_DIR_ROWS.equals(groupDir)) myGroupDir = Block.Direction.VERTICAL; else if (GROUP_DIR_COLS.equals(groupDir)) myGroupDir = Block.Direction.HORIZONTAL; else if (GROUP_DIR_NONE.equals(groupDir)) myGroupDir = Block.Direction.NONE; amICollapsed = AttributeUtil.evaluateBoolean(attributes.get(ATTR_COLLAPSE), beans, false); }
/** * Validates the attributes for this <code>Tag</code>. This tag must be * bodiless. The type must be valid. */ @SuppressWarnings("unchecked") public void validateAttributes() throws TagParseException { super.validateAttributes(); if (!isBodiless()) throw new TagParseException("Hyperlink tags must not have a body."); TagContext context = getContext(); Map<String, Object> beans = context.getBeans(); Map<String, RichTextString> attributes = getAttributes(); String type = AttributeUtil.evaluateStringSpecificValues(attributes.get(ATTR_TYPE), beans, ATTR_TYPE, Arrays.asList(TYPE_URL, TYPE_EMAIL, TYPE_FILE, TYPE_DOC), TYPE_URL); if (TYPE_URL.equals(type)) myLinkType = Hyperlink.LINK_URL; else if (TYPE_EMAIL.equals(type)) myLinkType = Hyperlink.LINK_EMAIL; else if (TYPE_FILE.equals(type)) myLinkType = Hyperlink.LINK_FILE; else if (TYPE_DOC.equals(type)) myLinkType = Hyperlink.LINK_DOCUMENT; myAddress = AttributeUtil.evaluateStringNotNull(attributes.get(ATTR_ADDRESS), beans, ATTR_ADDRESS, null); myValue = attributes.get(ATTR_VALUE); }
/** * Validates the attributes for this <code>Tag</code>. Some optional * attributes are only valid for bodiless tags, and others are only valid * for tags without bodies. */ public void validateAttributes() { super.validateAttributes(); TagContext context = getContext(); Map<String, Object> beans = context.getBeans(); Map<String, RichTextString> attributes = getAttributes(); Block block = context.getBlock(); if (!isBodiless()) throw new TagParseException("SpanTag: Must be bodiless"); myValue = attributes.get(ATTR_VALUE); List<RichTextString> atLeastOne = Arrays.asList(attributes.get(ATTR_FACTOR), attributes.get(ATTR_ADJUST)); AttributeUtil.ensureAtLeastOneExists(atLeastOne, Arrays.asList(ATTR_FACTOR, ATTR_ADJUST)); myFactor = AttributeUtil.evaluateNonNegativeInt(attributes.get(ATTR_FACTOR), beans, ATTR_FACTOR, 1); myAdjust = AttributeUtil.evaluateInt(attributes.get(ATTR_ADJUST), beans, ATTR_ADJUST, 0); boolean explicitlyExpandingRight = AttributeUtil.evaluateBoolean(attributes.get(ATTR_EXPAND_RIGHT), beans, false); if (explicitlyExpandingRight) block.setDirection(Block.Direction.HORIZONTAL); else block.setDirection(Block.Direction.VERTICAL); }
/** * Validates the attributes for this <code>Tag</code>. Some optional * attributes are only valid for bodiless tags, and others are only valid * for tags without bodies. */ public void validateAttributes() { super.validateAttributes(); TagContext context = getContext(); Map<String, Object> beans = context.getBeans(); Map<String, RichTextString> attributes = getAttributes(); Block block = context.getBlock(); String elseAction = AttributeUtil.evaluateStringSpecificValues(attributes.get(ATTR_ELSE_ACTION), beans, ATTR_ELSE_ACTION, Arrays.asList(ELSE_ACTION_SHIFT_UP, ELSE_ACTION_SHIFT_LEFT, ELSE_ACTION_CLEAR, ELSE_ACTION_REMOVE), ELSE_ACTION_SHIFT_UP); if (elseAction != null) { if (ELSE_ACTION_SHIFT_UP.equalsIgnoreCase(elseAction)) block.setDirection(Block.Direction.VERTICAL); else if (ELSE_ACTION_SHIFT_LEFT.equalsIgnoreCase(elseAction)) block.setDirection(Block.Direction.HORIZONTAL); else if (ELSE_ACTION_CLEAR.equalsIgnoreCase(elseAction) || ELSE_ACTION_REMOVE.equalsIgnoreCase(elseAction)) block.setDirection(Block.Direction.NONE); myElseAction = elseAction; } }
/** * Validates the attributes for this <code>Tag</code>. The "start", "end", * and "step" attributes must evaluate to <code>int</code>s. If "step" is * not present, then it defaults to <code>1</code>. The "step" must not be * zero. It is possible for no loops to be processed if "step" is positive * and "start" is greater than "end", or if "step" is negative and "start" * is less than "end". */ @Override public void validateAttributes() throws TagParseException { super.validateAttributes(); if (isBodiless()) throw new TagParseException("For tags must have a body."); TagContext context = getContext(); Map<String, Object> beans = context.getBeans(); Map<String, RichTextString> attributes = getAttributes(); myVarName = AttributeUtil.evaluateString(attributes.get(ATTR_VAR), beans, null); myStart = AttributeUtil.evaluateInt(attributes.get(ATTR_START), beans, ATTR_START, 0); myEnd = AttributeUtil.evaluateInt(attributes.get(ATTR_END), beans, ATTR_END, 0); myStep = AttributeUtil.evaluateNonZeroInt(attributes.get(ATTR_STEP), beans, ATTR_STEP, 1); }
/** * Validates the attributes for this <code>Tag</code>. The "items" * attribute must be a <code>List</code>. The "parallel" attribute must be * a positive integer (defaults to 1). The "value" attribute must be a * valid <code>Aggregator</code> specification string. The "total" tag must * not have a body. */ @SuppressWarnings("unchecked") public void validateAttributes() throws TagParseException { super.validateAttributes(); if (!isBodiless()) throw new TagParseException("Total tags must not have a body."); TagContext context = getContext(); Map<String, Object> beans = context.getBeans(); Map<String, RichTextString> attributes = getAttributes(); myList = AttributeUtil.evaluateObject(attributes.get(ATTR_ITEMS), beans, ATTR_ITEMS, List.class, new ArrayList<Object>(0)); myParallelism = AttributeUtil.evaluatePositiveInt(attributes.get(ATTR_PARALLEL), beans, ATTR_PARALLEL, 1); String aggSpec = AttributeUtil.evaluateString(attributes.get(ATTR_VALUE), beans, null); myAggregator = Aggregator.getAggregator(aggSpec); }
/** * Find any <code>Expressions</code> embedded in the given string, evaluate * them, and replace the expressions with the resulting values. If the * entire string consists of one <code>Expression</code>, then the returned * value may be any <code>Object</code>. * * @param richTextString The rich text string, with possibly embedded * expressions. * @param helper A <code>CreationHelper</code> that can create the proper * <code>RichTextString</code>. * @param beans A <code>Map</code> mapping strings to objects. * @return A new string, with any embedded expressions replaced with the * expression string values. */ public static Object evaluateString(RichTextString richTextString, CreationHelper helper, Map<String, Object> beans) { String value = richTextString.getString(); List<Expression> expressions = getExpressions(value); if (value.startsWith(Expression.BEGIN_EXPR) && value.endsWith(Expression.END_EXPR) && expressions.size() == 1) { Expression expression = new Expression(value.substring(2, value.length() - 1)); Object result = expression.evaluate(beans); if (result instanceof String) { return RichTextStringUtil.replaceAll(richTextString, helper, value, (String) result, true); } else { return result; } } else { return replaceExpressions(richTextString, helper, expressions, beans); } }
/** * Replace all expressions with their evaluated results. This attempts to * preserve any formatting within the <code>RichTextString</code>. * @param richTextString The entire string, with possibly many expressions * and possibly embedded formatting. * @param helper A <code>CreationHelper</code> that can create the proper * <code>RichTextString</code>. * @param expressions A <code>List</code> of <code>Expressions</code>. * @param beans A <code>Map</code> of beans to provide context for the * <code>Expressions</code>. * @return A <code>RichTextString</code> with all expressions replaced with * their evaluated results, and formatted preserved as best as possible. */ private static RichTextString replaceExpressions(RichTextString richTextString, CreationHelper helper, List<Expression> expressions, Map<String, Object> beans) { ArrayList<String> exprStrings = new ArrayList<String>(expressions.size()); ArrayList<String> exprValues = new ArrayList<String>(expressions.size()); for (Expression expr : expressions) { exprStrings.add(BEGIN_EXPR + expr.myExpression + END_EXPR); Object result = expr.evaluate(beans); if (result != null) exprValues.add(result.toString()); else exprValues.add(""); } return RichTextStringUtil.replaceValues(richTextString, helper, exprStrings, exprValues); }
/** * Evaluates the given text, which may have embedded * <code>Expressions</code>, and attempts to extract an integer value from * the result, calling <code>toString()</code> on the result and parsing it * if necessary. If the text is null, then the result defaults to the given * default integer value. * @param text Text which may have embedded <code>Expressions</code>. * @param beans A <code>Map</code> of bean names to bean values. * @param attrName The attribute name. This is only used when constructing * an exception message. * @param def The default value if the text is null. * @return The integer result. * @throws TagParseException If the result of the evaluation of the text is * not a number. */ public static int evaluateInt(RichTextString text, Map<String, Object> beans, String attrName, int def) { int result; if (text == null) return def; Object obj = Expression.evaluateString(text.toString(), beans); if (obj instanceof Number) { result = ((Number) obj).intValue(); } else { try { result = Integer.parseInt(obj.toString()); } catch (NumberFormatException e) { throw new TagParseException("The \"" + attrName + "\" attribute must be an integer: " + text); } } return result; }
/** * Evaluates the given text, which may have embedded * <code>Expressions</code>, and attempts to extract a double value from * the result, calling <code>toString()</code> on the result and parsing it * if necessary. * @param text Text which may have embedded <code>Expressions</code>. * @param beans A <code>Map</code> of bean names to bean values. * @param attrName The attribute name. This is only used when constructing * an exception message. * @param def The default value if the text is null. * @return The double result. * @throws TagParseException If the result of the evaluation of the text is * not a number. */ public static double evaluateDouble(RichTextString text, Map<String, Object> beans, String attrName, double def) { double result; if (text == null) return def; Object obj = Expression.evaluateString(text.toString(), beans); if (obj instanceof Number) { result = ((Number) obj).doubleValue(); } else { try { result = Double.parseDouble(obj.toString()); } catch (NumberFormatException e) { throw new TagParseException("The \"" + attrName + "\" attribute must be a number: " + text); } } return result; }
/** * Evaluates the given text, which may have embedded * <code>Expressions</code>, and attempts to extract a <code>List</code> out * of the result, parsing a delimited list to create a list if necessary. * @param text Text which may have embedded <code>Expressions</code>. * @param beans A <code>Map</code> of bean names to bean values. * @param def The default value if the text is null. * @return A <code>List</code>. */ public static List<String> evaluateList(RichTextString text, Map<String, Object> beans, List<String> def) { List<String> result; if (text == null) return def; Object obj = Expression.evaluateString(text.toString(), beans); if (obj instanceof List) { List list = (List) obj; result = new ArrayList<String>(list.size()); for (Object item : list) result.add(item.toString()); } else { String[] items = obj.toString().split(SPEC_SEP); result = Arrays.asList(items); } return result; }
/** * Ensures that exactly one of the given attribute values exists. * @param attrValues A <code>List</code> of attribute values. * @param attrNames A <code>List</code> of attribute names. * @throws TagParseException If none of the attribute values is not null, or * if more than one attribute value is not null. */ public static void ensureExactlyOneExists(List<RichTextString> attrValues, List<String> attrNames) { int exists = 0; for (RichTextString text : attrValues) { if (text != null) { exists++; if (exists > 1) { throw new TagParseException("Exactly one attribute must be specified: " + attrNames.toString()); } } } if (exists != 1) { throw new TagParseException("Exactly one attribute must be specified: " + attrNames.toString()); } }
/** * Ensures that at most one of the given attribute values exists. * @param attrValues A <code>List</code> of attribute values. * @param attrNames A <code>List</code> of attribute names. * @throws TagParseException If more than one of the attribute values is not * null. * @since 0.4.0 */ public static void ensureAtMostOneExists(List<RichTextString> attrValues, List<String> attrNames) { int exists = 0; for (RichTextString text : attrValues) { if (text != null) { exists++; if (exists > 1) { throw new TagParseException("At most one attribute must be specified: " + attrNames.toString()); } } } if (exists != 1 && exists != 0) { throw new TagParseException("At most one attribute must be specified: " + attrNames.toString()); } }
/** * Gets the font index of the <code>Font</code> in use at the specified * position in the given <code>RichTextString</code>. * @param richTextString The <code>RichTextString</code>. * @param fmtIndex The 0-based index of the formatting run. * @return The font index: If HSSF, a <code>short</code>. If XSSF, an * <code>XSSFFont</code>. */ public static Object getFontAtIndex(RichTextString richTextString, int fmtIndex) { if (richTextString instanceof HSSFRichTextString) { // Returns a short. return ((HSSFRichTextString) richTextString).getFontAtIndex(fmtIndex); } else if (richTextString instanceof XSSFRichTextString) { try { // Instead of returning null, getFontAtIndex (eventually) throws a // NullPointerException. It extracts a "CTRElt" from an array, and // it extracts a "CTRPrElt" from the "CTRElt". The "CTRprElt" can // be null if there is no font at the formatting run. Then, when // creating a "CTFont", it calls a method on the null "CTRPrElt". // Return an XSSFFont. return ((XSSFRichTextString) richTextString).getFontAtIndex(fmtIndex); } catch (NullPointerException e) { // Detect this case and return null. if (DEBUG) System.err.println(" NullPointerException caught!"); return null; } } else throw new IllegalArgumentException("Unexpected RichTextString type: " + richTextString.getClass().getName() + ": " + richTextString.getString()); }
private Comment createCellComment( String author, String comment ) { // comments only supported for XLSX if ( data.sheet instanceof XSSFSheet ) { CreationHelper factory = data.wb.getCreationHelper(); Drawing drawing = data.sheet.createDrawingPatriarch(); ClientAnchor anchor = factory.createClientAnchor(); Comment cmt = drawing.createCellComment( anchor ); RichTextString str = factory.createRichTextString( comment ); cmt.setString( str ); cmt.setAuthor( author ); return cmt; } return null; }
private static Cell mockCell(String text, long index) { Cell cell = mock(Cell.class); RichTextString value = mock(RichTextString.class); when(value.getString()).thenReturn(text); when(cell.getColumnIndex()).thenReturn((int) index); when(cell.getCellTypeEnum()).thenReturn(CellType.STRING); when(cell.getRichStringCellValue()).thenReturn(value); return cell; }
private Font getFontForFormattingRun(RichTextString richText, int i) { if (richText instanceof HSSFRichTextString) { HSSFRichTextString hssfRichText = (HSSFRichTextString) richText; return ((PoiWorkbook.PoiHssfWorkbook) getWorkbook()).getFont(hssfRichText.getFontOfFormattingRun(i)).getFont(); } else { return getWorkbook().getFont(((XSSFRichTextString) richText).getFontOfFormattingRun(i)).getFont(); } }
public RichText toRichText(RichTextString rts) { String text = rts.getString(); // TODO: properly process tabs text = text.replace('\t', ' '); // tab text = text.replace((char) 160, ' '); // non-breaking space RichTextBuilder rtb = new RichTextBuilder(); int start = 0; for (int i = 0; i < rts.numFormattingRuns(); i++) { start = rts.getIndexOfFormattingRun(i); int end = i + 1 < rts.numFormattingRuns() ? rts.getIndexOfFormattingRun(i + 1) : rts.length(); if (start == end) { // skip empty continue; } Map<String, Object> properties = new HashMap<>(); // apply font attributes for formatting run Font runFont = getFontForFormattingRun(rts, i); properties.put(TextAttributes.FONT_FAMILY, runFont.getFamily()); properties.put(TextAttributes.FONT_SIZE, runFont.getSizeInPoints() + "pt"); properties.put(TextAttributes.COLOR, runFont.getColor().toString()); if (runFont.isBold()) { properties.put(TextAttributes.FONT_WEIGHT, "bold"); } if (runFont.isItalic()) { properties.put(TextAttributes.FONT_STYLE, "italic"); } if (runFont.isUnderlined()) { properties.put(TextAttributes.TEXT_DECORATION, "underline"); } if (runFont.isStrikeThrough()) { properties.put(TextAttributes.TEXT_DECORATION, "line-through"); } properties.put(TextAttributes.COLOR, runFont.getColor()); Style attr = Style.create("style", properties); push(rtb, TextAttributes.STYLE_START_RUN, attr ); rtb.append(text, start, end); push(rtb, TextAttributes.STYLE_END_RUN, attr ); start = end; } rtb.append(text, start, text.length()); return rtb.toRichText(); }
/** * Gets the Double value of a cell * * @param cell * @return */ private static Double getDoubleCellValue(Cell cell, Locale locale) throws ExcelImportInvalidCellValueException { Double doubleValue = null; int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_NUMERIC) { double numericValue = cell.getNumericCellValue(); try { doubleValue = new Double(numericValue); } catch (Exception e) { throw new ExcelImportInvalidCellValueException(String.valueOf(numericValue)); } } else { if (cellType == Cell.CELL_TYPE_STRING) { RichTextString richTextString = cell.getRichStringCellValue(); if (richTextString != null) { String stringValue = richTextString.getString(); if (stringValue != null) { stringValue = stringValue.trim(); if (!"".equals(stringValue)) { doubleValue = DoubleNumberFormatUtil.getInstance().parseGUI(stringValue, locale); if (doubleValue == null) { doubleValue = DoubleNumberFormatUtil.parseISO(stringValue); if (doubleValue == null) { throw new ExcelImportInvalidCellValueException(stringValue); } } } } } } else { throw new ExcelImportInvalidCellValueException(getStringCellValue(cell)); } } return doubleValue; }
/** * Gets the Double value of a cell * * @param cell * @return */ private static Date getDateCellValue(Cell cell, Locale locale) throws ExcelImportInvalidCellValueException { Date dateValue = null; int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_NUMERIC) { try { dateValue = cell.getDateCellValue(); } catch (Exception e) { throw new ExcelImportInvalidCellValueException(String.valueOf(cell.getNumericCellValue())); } } else { if (cellType == Cell.CELL_TYPE_STRING) { RichTextString richTextString = cell.getRichStringCellValue(); if (richTextString != null) { String stringValue = richTextString.getString(); if (stringValue != null) { stringValue = stringValue.trim(); if (!"".equals(stringValue)) { dateValue = DateTimeUtils.getInstance().parseGUIDate(stringValue, locale); if (dateValue == null) { dateValue = DateTimeUtils.getInstance().parseShortDate(stringValue, locale); if (dateValue == null) { dateValue = DateTimeUtils.getInstance().parseISODate(stringValue); if (dateValue == null) { throw new ExcelImportInvalidCellValueException(stringValue); } } } } } } } else { throw new ExcelImportInvalidCellValueException(getStringCellValue(cell)); } } return dateValue; }
/** * Gets the Double value of a cell * * @param cell * @return */ private static Date getDateTimeCellValue(Cell cell, Locale locale) throws ExcelImportInvalidCellValueException { Date dateValue = null; int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_NUMERIC) { try { dateValue = cell.getDateCellValue(); } catch (Exception e) { throw new ExcelImportInvalidCellValueException(String.valueOf(cell.getNumericCellValue())); } } else { if (cellType == Cell.CELL_TYPE_STRING) { RichTextString richTextString = cell.getRichStringCellValue(); if (richTextString != null) { String stringValue = richTextString.getString(); if (stringValue != null) { stringValue = stringValue.trim(); if (!"".equals(stringValue)) { dateValue = DateTimeUtils.getInstance().parseGUIDateTime(stringValue, locale); if (dateValue == null) { dateValue = DateTimeUtils.getInstance().parseShortDateTime(stringValue, locale); if (dateValue == null) { dateValue = DateTimeUtils.getInstance().parseISODateTime(stringValue); } } } } } } else { throw new ExcelImportInvalidCellValueException(getStringCellValue(cell)); } } return dateValue; }
/** * Gets the Double value of a cell * * @param cell * @return */ private static Boolean getBooleanCellValue(Cell cell) throws ExcelImportInvalidCellValueException { Boolean booleanValue = null; int cellType = cell.getCellType(); if (cellType == Cell.CELL_TYPE_BOOLEAN) { boolean boolCellValue = cell.getBooleanCellValue(); booleanValue = new Boolean(boolCellValue); } else { if (cellType == Cell.CELL_TYPE_STRING) { RichTextString richTextString = cell.getRichStringCellValue(); if (richTextString != null) { String stringValue = richTextString.getString(); if (stringValue != null) { stringValue = stringValue.trim(); if (!"".equals(stringValue)) { if ("true".equalsIgnoreCase(stringValue) || BooleanFields.TRUE_VALUE.equalsIgnoreCase(stringValue)) { booleanValue = new Boolean(true); } else { if ("false".equalsIgnoreCase(stringValue) || BooleanFields.FALSE_VALUE.equalsIgnoreCase(stringValue)) { booleanValue = new Boolean(false); } else { if (stringValue != null && !"".equals(stringValue.trim())) { throw new ExcelImportInvalidCellValueException(stringValue); } } } } } } } else { throw new ExcelImportInvalidCellValueException(getStringCellValue(cell)); } } return booleanValue; }
/** * @param aValue * The value to be set. May be <code>null</code>. * @return A new cell in the current row of the current sheet with the passed * value */ @Nonnull public Cell addCell (@Nullable final RichTextString aValue) { final Cell aCell = addCell (); aCell.setCellType (CellType.STRING); if (aValue != null) aCell.setCellValue (aValue); return aCell; }
@Test public void testGetCellValueObject () { for (final EExcelVersion eVersion : EExcelVersion.values ()) { final Workbook aWB = eVersion.createWorkbook (); final Sheet aSheet = aWB.createSheet (); final Row aRow = aSheet.createRow (0); final Cell aCell = aRow.createCell (0); // boolean aCell.setCellValue (true); assertEquals (Boolean.TRUE, ExcelReadHelper.getCellValueObject (aCell)); // int aCell.setCellValue (4711); assertEquals (Integer.valueOf (4711), ExcelReadHelper.getCellValueObject (aCell)); // long aCell.setCellValue (Long.MAX_VALUE); assertEquals (Long.valueOf (Long.MAX_VALUE), ExcelReadHelper.getCellValueObject (aCell)); // double aCell.setCellValue (3.11234); assertEquals (Double.valueOf (3.11234), ExcelReadHelper.getCellValueObject (aCell)); // String aCell.setCellValue ("Anyhow"); assertEquals ("Anyhow", ExcelReadHelper.getCellValueObject (aCell)); // Rich text string final Font aFont = aWB.createFont (); aFont.setItalic (true); final RichTextString aRTS = eVersion.createRichText ("Anyhow"); aRTS.applyFont (1, 3, aFont); aCell.setCellValue (aRTS); assertEquals ("Anyhow", ExcelReadHelper.getCellValueObject (aCell)); } }
public Topic getCommentTopic(Cell cell, TopicMap tm) throws TopicMapException { Comment comment = cell.getCellComment(); if(comment != null) { RichTextString rts = comment.getString(); String str = rts.getString(); String basename = str.replace('\n', ' '); basename = basename.replace('\r', ' '); basename = basename.replace('\t', ' '); Topic topic=getOrCreateTopic(tm, EXCEL_COMMENT_SI_PREFIX+"/"+urlEncode(basename), basename); topic.setData(getCommentTypeTopic(tm), tm.getTopic(XTMPSI.getLang(DEFAULT_LANG)), str); topic.addType(getCommentTypeTopic(tm)); return topic; } return null; }
/** * Validates the attributes for this <code>Tag</code>. This tag must be * bodiless. */ @SuppressWarnings("unchecked") public void validateAttributes() throws TagParseException { super.validateAttributes(); if (!isBodiless()) throw new TagParseException("Formula tags must not have a body."); TagContext context = getContext(); Map<String, Object> beans = context.getBeans(); Map<String, RichTextString> attributes = getAttributes(); RichTextString formulaBean = attributes.get(ATTR_BEAN); RichTextString formulaText = attributes.get(ATTR_TEXT); AttributeUtil.ensureExactlyOneExists(Arrays.asList(formulaBean, formulaText), Arrays.asList(ATTR_BEAN, ATTR_TEXT)); if (formulaBean != null) { myFormulaExpression = Expression.evaluateString("${" + formulaBean.toString() + "}", beans).toString(); } else if (formulaText != null) { myFormulaExpression = attributes.get(ATTR_TEXT).getString(); } if (DEBUG) System.err.println("myFormulaExpression = " + myFormulaExpression); RichTextString rtsIfError = attributes.get(ATTR_IF_ERROR); myIfErrorExpression = (rtsIfError != null) ? rtsIfError.getString() : null; }
/** * Validates the attributes for this <code>Tag</code>. This tag must be * bodiless. */ @SuppressWarnings("unchecked") public void validateAttributes() throws TagParseException { super.validateAttributes(); if (!isBodiless()) throw new TagParseException("Comment tags must not have a body."); TagContext context = getContext(); Map<String, Object> beans = context.getBeans(); Map<String, RichTextString> attributes = getAttributes(); myValue = attributes.get(ATTR_VALUE); myAuthor = attributes.get(ATTR_AUTHOR).getString(); myComment = attributes.get(ATTR_COMMENT); RichTextString rtsVisible = attributes.get(ATTR_VISIBLE); String attrVisible = (rtsVisible != null) ? rtsVisible.getString() : null; if (attrVisible != null) { Object test = Expression.evaluateString(attrVisible, beans); if (test instanceof Boolean) amIVisible = (Boolean) test; else amIVisible = Boolean.parseBoolean(test.toString()); } }
/** * Ensure that the past end action (if specified) is a valid value. Ensure * that the group direction (if specified) is a valid value. * @throws TagParseException If the attribute values are illegal or * unacceptable. */ protected void validateAttributes() throws TagParseException { super.validateAttributes(); TagContext context = getContext(); Map<String, Object> beans = context.getBeans(); Map<String, RichTextString> attributes = getAttributes(); Block block = context.getBlock(); amIExplicitlyCopyingRight = AttributeUtil.evaluateBoolean(attributes.get(ATTR_COPY_RIGHT), beans, false); if (amIExplicitlyCopyingRight) block.setDirection(Block.Direction.HORIZONTAL); amIFixed = AttributeUtil.evaluateBoolean(attributes.get(ATTR_FIXED), beans, false); String strPastEndAction = AttributeUtil.evaluateStringSpecificValues(attributes.get(ATTR_PAST_END_ACTION), beans, ATTR_PAST_END_ACTION, Arrays.asList(PAST_END_ACTION_CLEAR, PAST_END_ACTION_REMOVE), PAST_END_ACTION_CLEAR); if (PAST_END_ACTION_CLEAR.equalsIgnoreCase(strPastEndAction)) myPastEndAction = PastEndAction.CLEAR_CELL; else if (PAST_END_ACTION_REMOVE.equalsIgnoreCase(strPastEndAction)) myPastEndAction = PastEndAction.REMOVE_CELL; String strGroupDir = AttributeUtil.evaluateStringSpecificValues(attributes.get(ATTR_GROUP_DIR), beans, ATTR_GROUP_DIR, Arrays.asList(GROUP_DIR_ROWS, GROUP_DIR_COLS, GROUP_DIR_NONE), GROUP_DIR_NONE); if (GROUP_DIR_ROWS.equals(strGroupDir)) myGroupDir = Block.Direction.VERTICAL; else if (GROUP_DIR_COLS.equals(strGroupDir)) myGroupDir = Block.Direction.HORIZONTAL; else if (GROUP_DIR_NONE.equals(strGroupDir)) myGroupDir = Block.Direction.NONE; amICollapsed = AttributeUtil.evaluateBoolean(attributes.get(ATTR_COLLAPSE), beans, false); myTagLoopListener = AttributeUtil.evaluateObject(attributes.get(ATTR_ON_LOOP_PROCESSED), beans, ATTR_ON_LOOP_PROCESSED, TagLoopListener.class, null); }
/** * <p>Checks the <code>Tag's</code> attributes to ensure that certain * requirements are met:</p> * <ol> * <li>All required attributes are present, and * <li>All attributes present are recognized. * <li>All attributes are validated through the method * <code>validateAttributes</code> (i.e. that method doesn't throw an * <code>Exception</code>). * </ol> * <p>A <code>TagParseException</code> is thrown if not all conditions above * are not met.</p> * <p>This calls <code>validateAttributes</code> if all conditions are met.</p> * @throws TagParseException If the above listed conditions are not met. * @see #validateAttributes */ public void checkAttributes() { Map<String, RichTextString> attributes = getAttributes(); List<String> required = getRequiredAttributes(); List<String> optional = getOptionalAttributes(); // Ensure all required attributes are found. if (required != null) { for (String reqName : required) { if (!attributes.containsKey(reqName)) throw new TagParseException("Required attribute \"" + reqName + "\" not found for tag \"" + getName() + "\"."); } } // Ensure all attributes are in either the required list or in the // optional list. Set<String> keys = attributes.keySet(); for (String key : keys) { if ((required == null || !required.contains(key)) && (optional == null || !optional.contains(key))) { throw new TagParseException("Unrecognized attribute \"" + key + "\" for tag \"" + getName() + "\"."); } } // Validate the attributes. validateAttributes(); }
/** * Validates the attributes according to <code>Tag</code>-specific rules. * Subclasses that want to add to validate their own attributes, as well as * these attributes, must override this method, call * <code>super.validateAttributes</code>, and then validate their own * attributes. * @throws TagParseException If the attribute values are illegal or * unacceptable. */ protected void validateAttributes() throws TagParseException { TagContext context = getContext(); Map<String, Object> beans = context.getBeans(); Map<String, RichTextString> attributes = getAttributes(); myTagListener = AttributeUtil.evaluateObject(attributes.get(ATTR_ON_PROCESSED), beans, ATTR_ON_PROCESSED, TagListener.class, null); if (DEBUG) System.err.println("BT.vA: myTagListener is " + ((myTagListener != null) ? myTagListener.toString() : " null")); }
/** * Creates a <code>Tag</code>, looking in a specific namespace for a class * matching a specific tag name. The given <code>TagParser</code> supplies * the namespace, the tag name, and the attributes. If found, this creates * the <code>Tag</code> and gives it the given <code>TagContext</code>, else * it returns <code>null</code>. * @param parser A <code>TagParser</code> that has parsed tag text. * @param context The <code>TagContext</code>. * @param workbookContext The <code>WorkbookContext</code>. * @return A new <code>Tag</code>, or <code>null</code> if it couldn't be * created. * @throws TagParseException If there was a problem instantiating the * desired <code>Tag</code>. */ public Tag createTag(TagParser parser, TagContext context, WorkbookContext workbookContext) { if (parser == null) return null; String namespace = parser.getNamespace(); String tagName = parser.getTagName(); Map<String, RichTextString> attributes = parser.getAttributes(); if (namespace == null || tagName == null) return null; TagLibrary library = myRegistry.get(namespace); if (library == null) return null; Class<? extends Tag> tagClass = library.getTagMap().get(tagName); if (tagClass == null) return null; try { Tag tag = tagClass.newInstance(); tag.setContext(context); tag.setWorkbookContext(workbookContext); tag.setAttributes(attributes); tag.setBodiless(parser.isBodiless()); return tag; } catch (Exception e) { throw new TagParseException("Unable to create tag " + namespace + ":" + tagName, e); } }
/** * Evaluates the given text, which may have embedded * <code>Expressions</code>, and attempts to extract a boolean value from * the result, calling <code>Boolean.parseBoolean()</code> on the result if * necessary. If the text is null, then the result defaults to the given * default boolean value. * @param text Text which may have embedded <code>Expressions</code>. * @param beans A <code>Map</code> of bean names to bean values. * @param def The default value if the text is null. * @return The boolean result. */ public static boolean evaluateBoolean(RichTextString text, Map<String, Object> beans, boolean def) { boolean result; if (text == null) return def; Object obj = Expression.evaluateString(text.toString(), beans); if (obj instanceof Boolean) result = (Boolean) obj; else result = Boolean.parseBoolean(obj.toString()); return result; }
/** * Ensures that at least one of the given attribute values exists. * @param attrValues A <code>List</code> of attribute values. * @param attrNames A <code>List</code> of attribute names. * @throws TagParseException If all of the attribute values are null. * @since 0.4.0 */ public static void ensureAtLeastOneExists(List<RichTextString> attrValues, List<String> attrNames) { for (RichTextString text : attrValues) { if (text != null) return; } throw new TagParseException("At least one attribute must be specified: " + attrNames.toString()); }
/** * Replace all occurrences of the given collection expression name with the * given item name, in preparation for implicit collections processing * loops. * @param sheet The <code>Sheet</code> on which the <code>Block</code> lies. * @param block The <code>Block</code> in which to perform the replacement. * @param collExpr The collection expression string to replace. * @param itemName The item name that replaces the collection expression. */ public static void setUpBlockForImplicitCollectionAccess(Sheet sheet, Block block, String collExpr, String itemName) { int left = block.getLeftColNum(); int right = block.getRightColNum(); int top = block.getTopRowNum(); int bottom = block.getBottomRowNum(); CreationHelper helper = sheet.getWorkbook().getCreationHelper(); // Look at the given range of Cells in the given range of rows. for (int rowNum = top; rowNum <= bottom; rowNum++) { Row row = sheet.getRow(rowNum); if (row != null) { for (int cellNum = left; cellNum <= right; cellNum++) { Cell cell = row.getCell(cellNum); if (cell != null && cell.getCellType() == Cell.CELL_TYPE_STRING) { RichTextString value = cell.getRichStringCellValue(); cell.setCellValue(RichTextStringUtil.replaceAll( value, helper, collExpr, itemName, false, 0, true)); } } } } }
/** * Format a <code>RichTextString</code> that has already been created. * @param string A <code>RichTextString</code>. * @param numFormattingRuns The number of formatting runs. * @param formattingRuns A <code>List</code> of <code>FormattingRuns</code>. */ public static void formatString(RichTextString string, int numFormattingRuns, List<FormattingRun> formattingRuns) { // Apply the formatting runs. for (int i = 0; i < numFormattingRuns; i++) { FormattingRun run = formattingRuns.get(i); int begin = run.getBegin(); int end = begin + run.getLength(); Object font = run.getFont(); if (DEBUG) { System.err.println(" RTSU.cFS: Applying format (" + i + "): begin=" + begin + ", length=" + run.getLength() + ", font=" + font + " to string \"" + string.getString() + "\"."); } if (string instanceof HSSFRichTextString) string.applyFont(begin, end, (Short) font); else if (string instanceof XSSFRichTextString) { if (font != null) string.applyFont(begin, end, (XSSFFont) font); } else throw new IllegalArgumentException("Unexpected RichTextString type: " + string.getClass().getName() + ": " + string.getString()); } }