How to create a RichTextString using Apache POI framework in Java?

狂风中的少年 提交于 2021-02-10 18:44:53

问题


How to create a RichTextString for Microsoft Excel, using Apache POI framework in Java SE?


回答1:


From here and here for HSSF and XSSF:

HSSFCell hssfCell = row.createCell(idx);
//rich text consists of two runs
HSSFRichTextString richString = new HSSFRichTextString( "Hello, World!" );
richString.applyFont( 0, 6, font1 );
richString.applyFont( 6, 13, font2 );
hssfCell.setCellValue( richString );

XSSFRichTextString s1 = new XSSFRichTextString("Apache POI");
s1.applyFont(boldArial);
cell1.setCellValue(s1);



回答2:


To keep abstraction on Workbook level (your code will work for both cases - HSSF and XSSF) you can write more intelligent code:

Workbook objWorkbook = /*pass workbook as a param*/;
RichTextString richText = objWorkbook.getCreationHelper().createRichTextString("yourstring");



回答3:


From the Quick Guide:

Text boxes are created using a different call:

HSSFTextbox textbox1 = patriarch.createTextbox(
        new HSSFClientAnchor(0,0,0,0,(short)1,1,(short)2,2));
textbox1.setString(new HSSFRichTextString("This is a test") );

It's possible to use different fonts to style parts of the text in the textbox. Here's how:

HSSFFont font = wb.createFont();
font.setItalic(true);
font.setUnderline(HSSFFont.U_DOUBLE);
HSSFRichTextString string = new HSSFRichTextString("Woo!!!");
string.applyFont(2,5,font);
textbox.setString(string );


来源:https://stackoverflow.com/questions/6911934/how-to-create-a-richtextstring-using-apache-poi-framework-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!