Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

java - How can I use predefined formats in DOCX with POI?

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

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

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");

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

  1. Create an empty docx file with Word 2007.
  2. Use this file as a template for your XWPFDocument
  3. Add your paragraphs with the styles.

Here's the code:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...