org.apache.poi.ss.usermodel.RichTextString Java Examples

The following examples show how to use org.apache.poi.ss.usermodel.RichTextString. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExcelExportOfTemplateUtil.java    From jeewx with Apache License 2.0 7 votes vote down vote up
/**
 * 创建文本类型的Cell
 * 
 * @param row
 * @param index
 * @param text
 * @param style
 * @param entity
 * @param workbook
 */
private static void createStringCell(Row row, int index, String text,
		ExcelExportEntity entity, Workbook workbook) {
	Cell cell = row.createCell(index);
	switch (entity.getType()) {
	case 1:
		RichTextString Rtext = workbook instanceof HSSFWorkbook ? new HSSFRichTextString(
				text) : new XSSFRichTextString(text);
		cell.setCellValue(Rtext);
		break;
	case 2:
		cell.setCellType(Cell.CELL_TYPE_FORMULA);
		cell.setCellFormula(entity.getCellFormula());
		break;
	}
}
 
Example #2
Source File: ExcelPrinterBase.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void handleValueType( final Cell cell, final Object value, final Workbook workbook ) {
  if ( value instanceof RichTextString ) {
    cell.setCellValue( (RichTextString) value );
  } else if ( value instanceof Date ) {
    cell.setCellValue( (Date) value );
  } else if ( value instanceof Number ) {
    final Number number = (Number) value;
    cell.setCellValue( number.doubleValue() );
  } else if ( value instanceof Boolean ) {
    cell.setCellValue( Boolean.TRUE.equals( value ) );
  } else if ( RotatedTextDrawable.extract( value ) != null ) {
    final RotatedTextDrawable rotatedTextDrawable = RotatedTextDrawable.extract( value );
    cell.setCellValue( rotatedTextDrawable.getText() );
  } else { // Something we can't handle.
    if ( value == null ) {
      cell.setCellType( Cell.CELL_TYPE_BLANK );
    } else {
      cell.setCellValue( String.valueOf( value ) );
    }
  }
}
 
Example #3
Source File: ExcelWriterStep.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #4
Source File: ExcelWriterTransform.java    From hop with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #5
Source File: AbstractExcelExtractor.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #6
Source File: DefaultCellCommentHandler.java    From xlsmapper with Apache License 2.0 5 votes vote down vote up
/**
 * 既にコメントが設定されているときのコメントの装飾を設定する。
 * 既存のコメントの装飾をコピーするが、そのとき、1つ目のフォント設定のみとする。
 * 
 * @param toRichText コピー先
 * @param fromrichText コピー元
 */
protected void copyCommentFormat(final RichTextString toRichText, final RichTextString fromrichText) {
    
    if(toRichText instanceof XSSFRichTextString) {
        toRichText.applyFont(((XSSFRichTextString)fromrichText).getFontOfFormattingRun(0));
        
    } else if(toRichText instanceof HSSFRichTextString) {
        toRichText.applyFont(((HSSFRichTextString)fromrichText).getFontOfFormattingRun(0));
        
    } else {
        logger.warn("not suuported exdcel format comment : {}", toRichText.getClass().getName());
    }
    
}
 
Example #7
Source File: EncryptedCachedDiskStringsTable.java    From hadoopoffice with Apache License 2.0 5 votes vote down vote up
/**
 * Get an item from the shared string table
 * 
 * @param idx index of the entry
 * @return entry
 * 
 */
@Override
public RichTextString getItemAt(int idx) {
	try {
		return new XSSFRichTextString(this.getString(idx));
	} catch (IOException e) {
		LOG.error("Cannot read from temporary shared String table. Exception: " + e);
	}
	return new XSSFRichTextString("");
}
 
Example #8
Source File: AbstractExcelFactory.java    From myexcel with Apache License 2.0 5 votes vote down vote up
private void doSetInnerSpan(Cell cell, Td td) {
    if (td.getFonts() == null || td.getFonts().isEmpty()) {
        return;
    }
    RichTextString richText = isHssf ? new HSSFRichTextString(td.getContent()) : new XSSFRichTextString(td.getContent());
    for (com.github.liaochong.myexcel.core.parser.Font font : td.getFonts()) {
        Font f = FontStyle.getFont(font.getStyle(), fontMap, () -> workbook.createFont(), customColor);
        richText.applyFont(font.getStartIndex(), font.getEndIndex(), f);
    }
    cell.setCellValue(richText);
}
 
Example #9
Source File: RichTextRenderingIT.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testExcelRendering() throws Exception {
  URL resource = getClass().getResource( "rich-text-sample1.prpt" );
  ResourceManager mgr = new ResourceManager();
  MasterReport report = (MasterReport) mgr.createDirectly( resource, MasterReport.class ).getResource();
  report.getReportConfiguration()
      .setConfigProperty( ClassicEngineCoreModule.COMPLEX_TEXT_CONFIG_OVERRIDE_KEY, "true" );
  report.getReportHeader().getElement( 0 ).getStyle().setStyleProperty( TextStyleKeys.DIRECTION, TextDirection.LTR );
  report.getReportHeader().getElement( 1 ).getStyle().setStyleProperty( TextStyleKeys.DIRECTION, TextDirection.RTL );
  report.getReportHeader().removeElement( 0 );
  report.getReportHeader().getStyle().setStyleProperty( ElementStyleKeys.BACKGROUND_COLOR, Color.YELLOW );
  report.getReportFooter().clear();

  LogicalPageBox logicalPageBox = DebugReportRunner.layoutPage( report, 0 );

  RenderNode second = MatchFactory.findElementByName( logicalPageBox, "second" );
  assertTrue( second instanceof RenderBox );

  ExcelOutputProcessorMetaData metaData =
      new ExcelOutputProcessorMetaData( ExcelOutputProcessorMetaData.PAGINATION_FULL );
  metaData.initialize( report.getConfiguration() );

  XSSFWorkbook hssfWorkbook = new XSSFWorkbook();
  ExcelColorProducer colorProducer = new StaticExcelColorSupport();
  ExcelFontFactory ff = new ExcelFontFactory( hssfWorkbook, colorProducer );
  CreationHelper ch = hssfWorkbook.getCreationHelper();
  ExcelTextExtractor te = new ExcelTextExtractor( metaData, colorProducer, ch, ff );

  Object compute = te.compute( (RenderBox) second );
  assertTrue( compute instanceof RichTextString );
  XSSFRichTextString rt = (XSSFRichTextString) compute;
  assertEquals( 4, rt.numFormattingRuns() );
}
 
Example #10
Source File: RichTextRenderingIT.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testFastExcelRendering() throws Exception {
  URL resource = getClass().getResource( "rich-text-sample1.prpt" );
  ResourceManager mgr = new ResourceManager();
  MasterReport report = (MasterReport) mgr.createDirectly( resource, MasterReport.class ).getResource();
  report.getReportConfiguration()
      .setConfigProperty( ClassicEngineCoreModule.COMPLEX_TEXT_CONFIG_OVERRIDE_KEY, "true" );
  report.getReportHeader().getElement( 0 ).getStyle().setStyleProperty( TextStyleKeys.DIRECTION, TextDirection.LTR );
  report.getReportHeader().getElement( 1 ).getStyle().setStyleProperty( TextStyleKeys.DIRECTION, TextDirection.RTL );
  report.getReportHeader().removeElement( 0 );
  report.getReportHeader().getStyle().setStyleProperty( ElementStyleKeys.BACKGROUND_COLOR, Color.YELLOW );
  report.getReportFooter().clear();

  ExpressionRuntime runtime =
      new GenericExpressionRuntime( new DefaultTableModel(), 0, new DefaultProcessingContext( report ) );

  RichTextStyleResolver resolver = new RichTextStyleResolver( runtime.getProcessingContext(), report );
  resolver.resolveRichTextStyle( report );

  XSSFWorkbook hssfWorkbook = new XSSFWorkbook();
  ExcelColorProducer colorProducer = new StaticExcelColorSupport();
  ExcelFontFactory ff = new ExcelFontFactory( hssfWorkbook, colorProducer );
  CreationHelper ch = hssfWorkbook.getCreationHelper();
  FastExcelTextExtractor te = new FastExcelTextExtractor( colorProducer, ff, ch );

  Element element = report.getReportHeader().getElement( 0 );
  Object compute = te.compute( element, runtime );
  assertTrue( compute instanceof RichTextString );
  XSSFRichTextString rt = (XSSFRichTextString) compute;
  assertEquals( 4, rt.numFormattingRuns() );
}
 
Example #11
Source File: HSSFSimpleShape.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param string Sets the rich text string used by this object.
 */
public void setString(RichTextString string) {
    //TODO add other shape types which can not contain text
    if (getShapeType() == 0 || getShapeType() == OBJECT_TYPE_LINE){
        throw new IllegalStateException("Cannot set text for shape type: "+getShapeType());
    }
    HSSFRichTextString rtr = (HSSFRichTextString) string;
    // If font is not set we must set the default one
    if (rtr.numFormattingRuns() == 0) rtr.applyFont((short) 0);
    TextObjectRecord txo = getOrCreateTextObjRecord();
    txo.setStr(rtr);
    if (string.getString() != null){
        setPropertyValue(new EscherSimpleProperty(EscherProperties.TEXT__TEXTID, string.getString().hashCode()));
    }
}
 
Example #12
Source File: SpreadsheetCell.java    From taro with MIT License 5 votes vote down vote up
public SpreadsheetCell setValue(Object value) {
    if (value == null) {
        cell.setCellValue((String)null);
    } else if (value instanceof String) {
        if (((String) value).startsWith("=")) {
            cell.setCellFormula(((String) value).substring(1));
        } else {
            cell.setCellValue((String)value);
        }
    } else if (value instanceof Number) {
        Double num = ((Number)value).doubleValue();
        if (num.isNaN() || num.isInfinite()) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(num);
        }
    } else if (value instanceof Date) {
        cell.setCellValue((Date)value);
    } else if (value instanceof Calendar) {
        cell.setCellValue((Calendar)value);
    } else if (value instanceof Boolean) {
        cell.setCellValue((Boolean)value);
    } else if (value instanceof RichTextString) {
        cell.setCellValue((RichTextString)value);
    } else {
        throw new TaroSpreadsheetException(format("Cannot set a %s [%s] as the spreadsheet cell content.",
                value.getClass().getSimpleName(), value.toString()));
    }
    return this;
}
 
Example #13
Source File: DefaultCellCommentHandler.java    From xlsmapper with Apache License 2.0 4 votes vote down vote up
@Override
public void handleSave(final Cell cell, final Optional<String> text, final Optional<XlsCommentOption> commentOption) {
    
    if(!text.isPresent()) {
        // コメントが空のとき
        commentOption.ifPresent(option -> {
            if(option.removeIfEmpty()) {
                // コメントが空のとき既存のコメントを削除する
                cell.removeCellComment();
            }
        });
        return;
    }
    
    final Sheet sheet = cell.getSheet();
    final CreationHelper helper = sheet.getWorkbook().getCreationHelper();
    final Drawing<?> drawing = sheet.createDrawingPatriarch();
    
    final Comment comment;
    RichTextString richText = helper.createRichTextString(text.get());
    if(cell.getCellComment() == null) {
        ClientAnchor anchor = createAnchor(drawing, text.get(), cell, commentOption);
        comment = drawing.createCellComment(anchor);
        applyCommentFormat(richText, cell);
    } else {
        // 既存のコメントが存在する場合は、書式やサイズをコピーして使用する。
        comment = cell.getCellComment();
        RichTextString orgText = comment.getString();
        if(orgText.numFormattingRuns() > 0) {
            copyCommentFormat(richText, orgText);
        } else {
            applyCommentFormat(richText, cell);
        }
    }
    
    comment.setString(richText);
    
    // コメントの表示状態の更新
    commentOption.ifPresent(option -> comment.setVisible(option.visible()));
    
    cell.setCellComment(comment);
    
}
 
Example #14
Source File: StreamingCell.java    From excel-streaming-reader with Apache License 2.0 4 votes vote down vote up
/**
 * Not supported
 */
@Override
public void setCellValue(RichTextString value) {
  throw new NotSupportedException();
}
 
Example #15
Source File: StyleManagerXUtils.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public RichTextString createRichTextString(String value) {
	XSSFRichTextString result = new XSSFRichTextString(value);
	return result;
}
 
Example #16
Source File: BufferedStringsTable.java    From excel-streaming-reader with Apache License 2.0 4 votes vote down vote up
@Override
public RichTextString getItemAt(int idx) {
  return new XSSFRichTextString(list.getAt(idx));
}
 
Example #17
Source File: CellContentHandler.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Set the contents of an empty cell.
 * This should now be the only way in which a cell value is set (cells should not be modified). 
 * @param value
 * The value to set.
 * @param element
 * The BIRT element supplying the value, used to set the style of the cell.
 */
private <T> void setCellContents(Cell cell, Object value) {
	log.debug( "Setting cell[", cell.getRow().getRowNum(), ",", cell.getColumnIndex(), "] value to ", value );
	if( value instanceof Double ) {
		// cell.setCellType(Cell.CELL_TYPE_NUMERIC);
		cell.setCellValue((Double)value);
		lastValue = value;
	} else if( value instanceof Integer ) {
		// cell.setCellType(Cell.CELL_TYPE_NUMERIC);
		cell.setCellValue((Integer)value);				
		lastValue = value;
	} else if( value instanceof Long ) {
		// cell.setCellType(Cell.CELL_TYPE_NUMERIC);
		cell.setCellValue((Long)value);				
		lastValue = value;
	} else if( value instanceof Date ) {
		// cell.setCellType(Cell.CELL_TYPE_NUMERIC);
		cell.setCellValue((Date)value);
		lastValue = value;
	} else if( value instanceof Boolean ) {
		// cell.setCellType(Cell.CELL_TYPE_BOOLEAN);
		cell.setCellValue(((Boolean)value).booleanValue());
		lastValue = value;
	} else if( value instanceof BigDecimal ) {
		// cell.setCellType(Cell.CELL_TYPE_NUMERIC);
		cell.setCellValue(((BigDecimal)value).doubleValue());				
		lastValue = value;
	} else if( value instanceof String ) {
		// cell.setCellType(Cell.CELL_TYPE_STRING);
		cell.setCellValue((String)value);				
		lastValue = value;
	} else if( value instanceof RichTextString ) {
		// cell.setCellType(Cell.CELL_TYPE_STRING);
		cell.setCellValue((RichTextString)value);				
		lastValue = value;
	} else if( value != null ){
		log.debug( "Unhandled data: ", ( value == null ? "<null>" : value ) );
		// cell.setCellType(Cell.CELL_TYPE_STRING);
		cell.setCellValue(value.toString());				
		lastValue = value;
	}
}
 
Example #18
Source File: StyleManagerHUtils.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public RichTextString createRichTextString(String value) {
	return new HSSFRichTextString(value);
}
 
Example #19
Source File: Excel2007Writer.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
public void witerTmxTU(List<TmxTU> tus, boolean writeFullText) throws IOException {

		if (null == tus || tus.isEmpty()) {
			return;
		}
		TmxTU tu = null;
		List<TmxSegement> temp = new ArrayList<TmxSegement>(5);
		int i = 0;
		for (; i < tus.size(); i++) {
			temp.clear();
			tu = tus.get(i);
			if (tu.getSource() != null) {
				temp.add(tu.getSource());
			}

			if (tu.getSegments() != null) {
				temp.addAll(tu.getSegments());
			}
			Row row = sh.createRow((lastIndex + i));

			// 为每一行添加数据
			for (TmxSegement segment : temp) {
				int cellIndex = getLangIndex(rowHeader, segment);
				if (-1 == cellIndex) {
					cellIndex = addLangCell(rowHeader, segment);
				}
				RichTextString createRichTextString = null;
				if (writeFullText) {
					createRichTextString = createHelper.createRichTextString(TextUtil.resetSpecialString(segment.getFullText()));
				} else {
					createRichTextString = createHelper.createRichTextString(TextUtil.resetSpecialString(segment.getPureText()));
				}
				Cell createCell = row.createCell(cellIndex);
				createCell.setCellStyle(getWrapedCell());	
				createCell.setCellValue(createRichTextString);
			}
		}
		lastIndex = lastIndex + i;
		// :使用固定的列宽
		// 设置宽度:此处比较耗时
		// for(Cell cell : rowHeader){
		// sheet.autoSizeColumn(cell.getColumnIndex());
		// }
		tus.clear();
	}
 
Example #20
Source File: Excel2007Writer.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
public void witerTmxTU(List<TmxTU> tus, boolean writeFullText) throws IOException {

		if (null == tus || tus.isEmpty()) {
			return;
		}
		TmxTU tu = null;
		List<TmxSegement> temp = new ArrayList<TmxSegement>(5);
		int i = 0;
		for (; i < tus.size(); i++) {
			temp.clear();
			tu = tus.get(i);
			if (tu.getSource() != null) {
				temp.add(tu.getSource());
			}

			if (tu.getSegments() != null) {
				temp.addAll(tu.getSegments());
			}
			Row row = sh.createRow((lastIndex + i));

			// 为每一行添加数据
			for (TmxSegement segment : temp) {
				int cellIndex = getLangIndex(rowHeader, segment);
				if (-1 == cellIndex) {
					cellIndex = addLangCell(rowHeader, segment);
				}
				RichTextString createRichTextString = null;
				if (writeFullText) {
					createRichTextString = createHelper.createRichTextString(segment.getFullText());
				} else {
					createRichTextString = createHelper.createRichTextString(segment.getPureText());
				}
				Cell createCell = row.createCell(cellIndex);
				createCell.setCellStyle(getWrapedCell());
				createCell.setCellValue(createRichTextString);
			}
		}
		lastIndex = lastIndex + i;
		// :使用固定的列宽
		// 设置宽度:此处比较耗时
		// for(Cell cell : rowHeader){
		// sheet.autoSizeColumn(cell.getColumnIndex());
		// }
		tus.clear();
	}
 
Example #21
Source File: JRXlsMetadataExporter.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void writeCurrentRow(Map<String, Object> currentRow, Map<String, Object> repeatedValues)  throws JRException {
	row = sheet.createRow(sheet.getPhysicalNumberOfRows());
	setRowHeight(row);
	
	for(int i = 0; i< columnNames.size(); i++) {
		String columnName = columnNames.get(i);
		CellSettings cellSettings = (CellSettings)currentRow.get(columnName) == null 
			? (repeatedValues.get(columnName) != null 
			? (CellSettings)repeatedValues.get(columnName)
			: null)
			: (CellSettings)currentRow.get(columnName);
		cell = row.createCell(i);
		if(cellSettings != null) {
			CellType type = cellSettings.getCellType();
			cell.setCellType(type);
			Object cellValue = cellSettings.getCellValue();
			if(cellValue != null) {
				if(cellValue instanceof RichTextString) {
					cell.setCellValue((RichTextString)cellSettings.getCellValue());
				} else if (cellValue instanceof Number) {
					cell.setCellValue(((Number)cellSettings.getCellValue()).doubleValue());
				} else if (cellValue instanceof Date) {
					cell.setCellValue((Date)cellSettings.getCellValue());
				} else if(cellValue instanceof Boolean) {
					cell.setCellValue((Boolean)cellSettings.getCellValue());
				}else if(cellValue instanceof ImageSettings){
					ImageSettings imageSettings = (ImageSettings)cellValue;
					try {
						HSSFClientAnchor anchor = 
								new HSSFClientAnchor(
									0, 
									0, 
									0, 
									0, 
									(short)(i), 
									rowIndex, 
									(short)(i + 1), 
									rowIndex+1
									);
						anchor.setAnchorType(imageSettings.getAnchorType());
						patriarch.createPicture(anchor, imageSettings.getIndex());
					} catch (Exception ex) {
						throw 
							new JRException(
								EXCEPTION_MESSAGE_KEY_CANNOT_ADD_CELL, 
								null,
								ex);
					} catch (Error err) {
						throw 
							new JRException(
								EXCEPTION_MESSAGE_KEY_CANNOT_ADD_CELL, 
								null,
								err);
					}
				}
			}
			
			if(cellSettings.getCellStyle() != null) {
				cell.setCellStyle(cellSettings.getCellStyle());
			}
			if(cellSettings.getFormula() != null) {
				// the formula text will be stored in formulaCellsMap in order to be applied only after 
				// all defined names are created and available in the workbook (see #closeWorkbook())
				formulaCellsMap.put(cell, cellSettings.getFormula());
			}
			if(cellSettings.getLink() != null) {
				cell.setHyperlink(cellSettings.getLink());
			}
		}
	}
	++rowIndex;
}
 
Example #22
Source File: JavaToExcel.java    From hy.common.report with Apache License 2.0 4 votes vote down vote up
/**
 * 复制单位格(空白行的复制,即只复制格式和固定文字,不填充数据)
 * 
 * @author      ZhengWei(HY)
 * @createDate  2017-07-03
 * @version     v1.0
 *
 * @param i_RTemplate      模板对象
 * @param i_TemplateCell   模板中的单元格对象
 * @param i_DataWorkbook   数据工作薄
 * @param i_DataCell       数据中的单元格对象
 * @param io_RSystemValue 系统变量信息
 * @param i_Datas          本行对应的数据
 * @param io_RValue        小计循环的迭代器
 * @return                 
 */
public final static void copyCellByBlankSpace(RTemplate i_RTemplate ,Cell i_TemplateCell ,RWorkbook i_DataWorkbook ,Cell i_DataCell ,RSystemValue io_RSystemValue)
{
    // 复制样式
    i_DataCell.setCellStyle(i_DataWorkbook.getCellStyle(i_RTemplate ,i_TemplateCell.getCellStyle().getIndex()));
    
    // 复制评论
    copyComment(i_RTemplate ,i_TemplateCell ,i_DataWorkbook ,i_DataCell);
    
    // 复制数据类型
    CellType v_CellType = i_TemplateCell.getCellTypeEnum();
    // i_DataCell.setCellType(v_CellType);  不能在此统一设置,原因是:下面代码对类型是有浮动的
    
    if ( v_CellType == CellType.NUMERIC ) 
    {
        i_DataCell.setCellType(v_CellType);
        
        if ( HSSFDateUtil.isCellDateFormatted(i_TemplateCell) ) 
        {
            i_DataCell.setCellValue(i_TemplateCell.getDateCellValue());
        } 
        else 
        {
            i_DataCell.setCellValue(i_TemplateCell.getNumericCellValue());
        }
    }
    else if ( v_CellType == CellType.STRING ) 
    {
        RichTextString v_TemplateRichText = i_TemplateCell.getRichStringCellValue();
        String         v_ValueName        = v_TemplateRichText.toString();
        
        if ( i_RTemplate.isExists(v_ValueName) )
        {
            i_DataCell.setCellType(v_CellType);
            i_DataCell.setCellValue("");
        }
        else 
        {
            i_DataCell.setCellType(v_CellType);
            copyRichTextStyle(i_RTemplate ,v_TemplateRichText ,i_DataWorkbook ,i_DataCell);
        }
    } 
    else if ( v_CellType == CellType.BOOLEAN ) 
    {
        i_DataCell.setCellType(v_CellType);
        i_DataCell.setCellValue(i_TemplateCell.getBooleanCellValue());
    } 
    else if ( v_CellType == CellType.FORMULA) 
    {
        i_DataCell.setCellType(v_CellType);
        i_DataCell.setCellFormula(ExcelFormula.calcFormulaOffset(i_TemplateCell ,i_DataCell));
    } 
    else 
    {
        // Nothing.
        i_DataCell.setCellType(v_CellType);
    }
}
 
Example #23
Source File: ReadOnlySharedStringsTable.java    From myexcel with Apache License 2.0 4 votes vote down vote up
@Override
public RichTextString getItemAt(int idx) {
    return new XSSFRichTextString(stringsCache.get(idx));
}
 
Example #24
Source File: HSSFCell.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Set a string value for the cell.
 *
 * @param value  value to set the cell to.  For formulas we'll set the formula
 * string, for String cells we'll set its value.  For other types we will
 * change the cell to a string cell and set its value.
 * If value is <code>null</code> then we will change the cell to a Blank cell.
 */

public void setCellValue(RichTextString value)
{
    int row=_record.getRow();
    short col=_record.getColumn();
    short styleIndex=_record.getXFIndex();
    if (value == null)
    {
        notifyFormulaChanging();
        setCellType(CellType.BLANK, false, row, col, styleIndex);
        return;
    }

    if(value.length() > SpreadsheetVersion.EXCEL97.getMaxTextLength()){
        throw new IllegalArgumentException("The maximum length of cell contents (text) is 32,767 characters");
    }

    if (_cellType == CellType.FORMULA) {
        // Set the 'pre-evaluated result' for the formula
        // note - formulas do not preserve text formatting.
        FormulaRecordAggregate fr = (FormulaRecordAggregate) _record;
        fr.setCachedStringResult(value.getString());
        // Update our local cache to the un-formatted version
        _stringValue = new HSSFRichTextString(value.getString());

        // All done
        return;
    }

    // If we get here, we're not dealing with a formula,
    //  so handle things as a normal rich text cell

    if (_cellType != CellType.STRING) {
        setCellType(CellType.STRING, false, row, col, styleIndex);
    }
    int index = 0;

    HSSFRichTextString hvalue = (HSSFRichTextString) value;
    UnicodeString str = hvalue.getUnicodeString();
    index = _book.getWorkbook().addSSTString(str);
    (( LabelSSTRecord ) _record).setSSTIndex(index);
    _stringValue = hvalue;
    _stringValue.setWorkbookReferences(_book.getWorkbook(), (( LabelSSTRecord ) _record));
    _stringValue.setUnicodeString(_book.getWorkbook().getSSTString(index));
}
 
Example #25
Source File: HSSFFormulaEvaluator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected RichTextString createRichTextString(String str) {
    return new HSSFRichTextString(str);
}
 
Example #26
Source File: ExcelExportUtil.java    From jeewx with Apache License 2.0 3 votes vote down vote up
/**
 * 创建文本类型的Cell
 * 
 * @param row
 * @param index
 * @param text
 * @param style
 * @param entity 
 */
private static void createStringCell(Row row, int index, String text,
		CellStyle style, ExcelExportEntity entity) {
	Cell cell = row.createCell(index);
	RichTextString Rtext = new HSSFRichTextString(text);
	cell.setCellValue(Rtext);
	cell.setCellStyle(style);
}
 
Example #27
Source File: StyleManagerUtils.java    From birt with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Create a RichTextString representing a given string.
 * @param value
 * The string to represent in the RichTextString.
 * @return
 * A RichTextString representing value.
 */
public abstract RichTextString createRichTextString(String value);
 
Example #28
Source File: DefaultCellCommentHandler.java    From xlsmapper with Apache License 2.0 2 votes vote down vote up
/**
 * 新規にコメントの装飾を設定する。
 * セルの装飾に合わせる。
 * 
 * @param toRichText 設定先のコメント
 * @param cell コメントを設定する先のセル
 */
protected void applyCommentFormat(final RichTextString toRichText, final Cell cell) {
    
    toRichText.applyFont(cell.getCellStyle().getFontIndex());
}
 
Example #29
Source File: BaseFormulaEvaluator.java    From lams with GNU General Public License v2.0 votes vote down vote up
protected abstract RichTextString createRichTextString(String str);