通过一些图书馆,例如http://poi.apache.org http://poi.apache.org,我们可以创建Word文档具有任何文本颜色,但对于背景或文本的突出显示,我没有找到任何解决方案。
手动方式的word页面颜色!:
https://support.office.com/en-us/article/Change-the-background-or-color-of-a-document-6ce0b23e-b833-4421-b8c3-b3d637e62524 https://support.office.com/en-us/article/Change-the-background-or-color-of-a-document-6ce0b23e-b833-4421-b8c3-b3d637e62524
这是我通过 poi.apache 创建 Word 文档的主要代码
// Blank Document
@SuppressWarnings("resource")
XWPFDocument document = new XWPFDocument();
// Write the Document in file system
FileOutputStream out = new FileOutputStream(new File(file_address));
// create Paragraph
XWPFParagraph paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
XWPFRun run = paragraph.createRun();
run.setFontFamily(font_name);
run.setFontSize(font_size);
// This only set text color not background!
run.setColor(hex_color);
for (String s : text_array) {
run.setText(s);
run.addCarriageReturn();
}
document.write(out);
out.close();
更新:XWPF 是创建 Word 文档文件的最新方法,但设置背景只能通过 HWPF 进行,这是针对旧格式版本 (.doc)
对于 *.doc(即 POI 的 HWPF 组件):
文本突出显示:
调查setHighlighted() https://poi.apache.org/apidocs/org/apache/poi/hwpf/usermodel/CharacterRun.html#setHighlighted%28byte%29
-
背景颜色:
我想你的意思是一个段落的背景(据我所知,Word还允许为整个页面着色,这是另一回事)
有setShading() https://poi.apache.org/apidocs/org/apache/poi/hwpf/usermodel/Paragraph.html#setShading%28org.apache.poi.hwpf.usermodel.ShadingDescriptor%29它允许您提供前景色和背景色(通过setCvFore()
and setCvBack()
of SHDAbstractType
) 为一个段落。 IIRC,它是前景您想要设置以便为段落着色。这背景仅与由两种(交替)颜色组成的阴影相关。
底层数据结构被命名为Shd80
([MS-DOC],2.9.248)。还有SHDOperand
([MS-DOC],2.9.249)反映了 Word97 之前的 Word 的功能。 [MS-DOC] 是二进制 Word 文件格式规范,可在 MSDN 上免费获取。
Edit:
下面是一些代码来说明上述内容:
try {
HWPFDocument document = [...]; // comes from somewhere
Range range = document.getRange();
// Background shading of a paragraph
ParagraphProperties pprops = new ParagraphProperties();
ShadingDescriptor shd = new ShadingDescriptor();
shd.setCvFore(Colorref.valueOfIco(0x07)); // yellow; ICO
shd.setIpat(0x0001); // solid background; IPAT
pprops.setShading(shd);
Paragraph p1 = range.insertBefore(pprops, StyleSheet.NIL_STYLE);
p1.insertBefore("shaded paragraph");
// Highlighting of individual characters
Paragraph p2 = range.insertBefore(new ParagraphProperties(), StyleSheet.NIL_STYLE);
CharacterRun cr = p2.insertBefore("highlighted text\r");
cr.setHighlighted((byte) 0x06); // red; ICO
document.write([...]); // document goes to somewhere
} catch (IOException e) {
e.printStackTrace();
}
-
ICO https://msdn.microsoft.com/en-us/library/dd773060%28v=office.12%29.aspx是一个颜色结构
-
IPAT https://msdn.microsoft.com/en-us/library/dd945712%28v=office.12%29.aspx是预定义着色样式的列表
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)