如何将 DOCX 中的预定义格式与 POI 一起使用? [英] How can I use predefined formats in DOCX with POI?

查看:22
本文介绍了如何将 DOCX 中的预定义格式与 POI 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个带有 POI 的 docx 生成器,并希望使用预定义的格式.

I'm creating a docx generator with POI and would like to use predefined formats.

Word 包含多种格式,如标题、标题 1..10 等.这些格式在您使用 Word 创建的每个 DOCX 中都是预定义的.

Word includes several formats like Title, Heading 1..10 etc. These formats are predefined in every DOCX you create with Word.

我想在我的 docx 生成器中使用它们.我尝试了以下但未应用格式:

I would like to use them in my docx generator. I tried the following but the format was not applied:

paragraph = document.createParagraph();
lastParagraph.setStyle("Heading1");

我还尝试将标题 1"、标题 1"和标题 1"作为样式,但都没有奏效.
API 文档 不显示任何细节.

I also tried "heading 1", "heading1" and "Heading1" as style, but none of them worked.
The API documentation doesn't show any details.

我分析了一个用 Word 2007 创建的 docx 文件,发现标题 1"是正确的.不幸的是,该样式未在 docx 中定义.我必须手动创建此样式吗?

I analysed a docx file created with Word 2007 and found out "Heading1" would be correct. Unfortunately, the style is not defined in the docx. Do I have to create this style manually?

谁能给我指出正确的解决方案?

Can anyone point me to the correct solution?

推荐答案

很简单:使用模板"docx 文件.

It's very simple: Use a "template" docx file.

  1. 使用 Word 2007 创建一个空的 docx 文件.
  2. 将此文件用作XWPFDocument的模板
  3. 使用样式添加段落.

代码如下:

XWPFDocument document = new XWPFDocument(new FileInputStream("template.docx");
paragraph = document.createParagraph();
paragraph.setStyle("Heading1");

模板包含所有样式,因此它们可以通过 setStyle("Heading1"); 引用.

The template contains all styles and therefore they can referenced via setStyle("Heading1");.

这篇关于如何将 DOCX 中的预定义格式与 POI 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆