Last active
March 15, 2019 02:47
-
-
Save xpalive/e2cdd3847d60871ed0fe3e3545f6d2a7 to your computer and use it in GitHub Desktop.
poi生成word时设置段落样式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
POI生成Word时,设置段落的样式 | |
String style = "2"; //标题2的样式(这个值,我发现不同的文档值都不一样。。这里只是一个例子) | |
XWPFParagraph xwpfParagraph = doc.insertNewParagraph(run); | |
xwpfParagraph.setStyle(style); | |
其实设置其他的样式都一样。 | |
例如:你想设置你的样式为“标题2”(“标题2”只是你在word里看到的标题名称,实际上在xml中的名称可能不一样) | |
word里:我是标题2的样式 --这个段落在word里设置了标题2的样式 | |
xml里: | |
<w:p w:rsidR="003275EA" w:rsidRDefault="007A6279" w:rsidP="003275EA"> | |
<w:pPr> | |
<w:pStyle w:val="2"/> <!-- 这里就是标题2样式的值 --> | |
</w:pPr> | |
<w:r> | |
<w:rPr> | |
<w:rFonts w:hint="eastAsia"/> | |
</w:rPr> | |
<w:t>我</w:t> | |
</w:r> | |
<w:r> | |
<w:t>是标题</w:t> | |
</w:r> | |
<w:r> | |
<w:rPr> | |
<w:rFonts w:hint="eastAsia"/> | |
</w:rPr> | |
<w:t>2</w:t> | |
</w:r> | |
<w:r> | |
<w:rPr> | |
<w:rFonts w:hint="eastAsia"/> | |
</w:rPr> | |
<w:t>的样式</w:t> | |
</w:r> | |
</w:p> | |
而样式的定义是这样的(这些都可以在word转成xml的内容里找到): | |
<w:style w:type="paragraph" w:styleId="2"> <!-- 这里就是我们使用的标题2 --> | |
<w:name w:val="heading 2"/> <!-- heading 2 是标题2 --> | |
<w:basedOn w:val="a"/> | |
<w:next w:val="a"/> | |
<w:link w:val="2Char"/> | |
<w:uiPriority w:val="9"/> | |
<w:unhideWhenUsed/> | |
<w:qFormat/> | |
<w:rsid w:val="003275EA"/> | |
<w:pPr> | |
<w:keepNext/> | |
<w:keepLines/> | |
<w:spacing w:before="260" w:after="260" w:line="416" w:lineRule="auto"/> | |
<w:outlineLvl w:val="1"/> | |
</w:pPr> | |
<w:rPr> | |
<w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi"/> | |
<w:b/> | |
<w:bCs/> | |
<w:sz w:val="32"/> | |
<w:szCs w:val="32"/> | |
</w:rPr> | |
</w:style> | |
到此我们就知道,设置段落样式“标题2”的方法就是: | |
xwpfParagraph.setStyle("2"); | |
问题来了! | |
如何知道样式的值呢? | |
代码如下: | |
/** | |
* 查找文档样式值 | |
* @param document 文档类 | |
* @param styleName 样式名称 | |
* @return 样式值 | |
* @throws IOException | |
* @throws XmlException | |
*/ | |
public static String getStyleValue(XWPFDocument document, String styleName) throws IOException, XmlException { | |
if (styleName == null || styleName.length() == 0) { | |
return null; | |
} | |
CTStyles styles = document.getStyle(); | |
CTStyle[] styleArray = styles.getStyleArray(); | |
for (CTStyle style : styleArray) { | |
if (style.getName().getVal().equals(styleName)) { | |
return style.getStyleId(); | |
} | |
} | |
return null; | |
} | |
在word里的样式名称是 标题 2,但xml里就是<w:name w:val="heading 2"/> ,所以使用word默认标题的时候使用heading 开头的就好了。 | |
自定义的标题,获取样式值的时候,直接用自定义的标题名称就好了。 | |
注意 | |
如果不生效,就先新建一个文档,把段落设置成想要的样式,然后看看段落样式的值是多少就可以了。 | |
我觉得大部分问题的解决方法都可以去看xml里的值,然后再用代码去设置值就好了。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment