如何在Java中为word文档(.doc或.docx)设置背景颜色(页面颜色)?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在Java中为word文档(.doc或.docx)设置背景颜色(页面颜色)?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2333字,纯文字阅读大概需要4分钟。
内容图文
![如何在Java中为word文档(.doc或.docx)设置背景颜色(页面颜色)?](/upload/InfoBanner/zyjiaocheng/698/07ebe47b8f2d4270a2129caf88260fea.jpg)
通过像http://poi.apache.org这样的库,我们可以用任何文本颜色创建word文档,但是对于文本的背景或突出显示,我没有找到任何解决方案.
手动方式的单词页面颜色!:
这是我通过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文档文件的最新方式,但只能通过旧格式版本(.doc)的HWPF设置背景
对于* .doc(即POI的HWPF组件):
>突出显示文字:
看看setHighlighted()
>背景颜色:
我想你的意思是段落的背景(AFAIK,Word也允许为整个页面着色,这是另一回事)
有一个setShading()允许您为段落提供前景色和背景色(通过SHDAbstractType的setCvFore()和setCvBack()). IIRC,它是您想要设置的前景,以便为您的段落着色.背景仅与由两种(交替)颜色组成的阴影相关.
基础数据结构名为Shd80([MS-DOC],2.9.248).还有SHDOperand([MS-DOC],2.9.249),它反映了Word97之前Word的功能. [MS-DOC]是二进制Word文件格式规范,可在MSDN上免费获得.
编辑:
以下是一些代码来说明以上内容:
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();
}
内容总结
以上是互联网集市为您收集整理的如何在Java中为word文档(.doc或.docx)设置背景颜色(页面颜色)?全部内容,希望文章能够帮你解决如何在Java中为word文档(.doc或.docx)设置背景颜色(页面颜色)?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。