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?
XWPF (XML Word Processor Format) − It is used to read and write . docx extension files of MS-Word. HSLF (Horrible Slide Layout Format) − It is used to read, create, and edit PowerPoint presentations.
It's very simple: Use a "template" docx file.
XWPFDocument
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");
.
You can create a word template (just use the Save as... feature in Word).
The template now contains a number of additional XML files in \word folder: - styles.xml - stylesWithEffects.xml - webSettings.xml - fontTable.xml and a - \theme folder
If you copy those files into your original POI generated file then you can reference styles given in the styles.xml file.
You can manipulate your original file like a ZIP file, this shouldn't be to much effort.
Copy styles in code from template to your document:
XWPFDocument template = new XWPFDocument(new FileInputStream(new File("Template.dotx")));
XWPFDocument doc = new XWPFDocument();
// let's copy styles from template to new doc
XWPFStyles newStyles = doc.createStyles();
newStyles.setStyles(template.getStyle());
XWPFParagraph para = doc.createParagraph();
para.setStyle("Heading1");
XWPFRun run = para.createRun();
run.setText("Heading 1");
return doc;
On the plus side you can manipulate your styles separately directly using Word and saving them back to the template file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With