tags:

views:

296

answers:

2

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?

+1  A: 

Yes, you should do it manually. Docx spec says that styles.xml which contains info about styles is optional. So, I almost sure that POI doesn't create it at all if you do not do it explicitely. You can check it: just unzip docx file and look whether this file is there or not (yourfile.docx/word/styles.xml).

So, what you should do (in docx terms, I don't know how that's implemented in POI):

1) create styles.xml and add necessary styles there

2) create relationship which connects document.xml and styles.xml (I think POI should do it automatically)

3) use styles ids inside document.xml to connect concrete text part (Run in docx terms) with concrete style.

Roman
Thanks for your answer! Your solution would be a huge effort to manually reproduce the styles.
furtelwart
+1  A: 

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();
lastParagraph.setStyle("Heading1");

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

furtelwart