2
votes

I am trying to create heading titles in a word (.docx) document, using apache-poi.

I have a template which contains only custom styles AND example of heading titles using the custom styles.

XWPFDocument document=new XWPFDocument(new FileInputStream("template.docx"));

My custom style is called "CUSTOM_YNP" (I created it directly in Word), but when I use the line below, it returns false

document.getStyles().styleExist("CUSTOM_YNP")

And, of course, when I try to use this style, it doesn't work, actually it print my string in "Normal" style

XWPFParagraph paragraph=document.createParagraph();
paragraph.setStyle("CUSTOM_YNP");
XWPFRun run=paragraph.createRun();
run.setText("TEST");

Just for the record, my "save document" line :

document.write(new FileOutputStream("myDoc.docx"));

I have read this question, but can't actually find a solution to my problem... How can I use predefined formats in DOCX with POI?

EDIT : It works if I create my own style using Apache-POI.... Still I woudl really like to use existing styles from the word document.

2

2 Answers

3
votes

A *.docx is a ZIP archive. You can unzip it and look into the /word/styles.xml. There you will see that the w:styleId="CUSTOMYNP" without the underscore. The name is "CUSTOM_YNP" <w:name w:val="CUSTOM_YNP"/>. So:

  XWPFDocument document = new XWPFDocument(new FileInputStream("template.docx"));

  System.out.println(document.getStyles().styleExist("CUSTOMYNP"));
  System.out.println(document.getStyles().getStyle("CUSTOMYNP").getName());

  XWPFParagraph paragraph=document.createParagraph();
  paragraph.setStyle("CUSTOMYNP");
  XWPFRun run=paragraph.createRun();
  run.setText("TEST");

  document.write(new FileOutputStream("myDoc.docx"));
  document.close();
1
votes

Make sure you first create the Style and add it to your document:

XWPFDocument document = new XWPFDocument();
XWPFStyles styles = document.createStyles();

String heading1 = "My Heading 1";
addCustomHeadingStyle(document, styles, heading1, 1, 36, "4288BC");

XWPFParagraph paragraph = document.createParagraph();
paragraph.setStyle(heading1);

With the addCustomHeadingStyle being:

private static void addCustomHeadingStyle(XWPFDocument docxDocument, XWPFStyles styles, String strStyleId, int headingLevel, int pointSize, String hexColor) {

    CTStyle ctStyle = CTStyle.Factory.newInstance();
    ...
    //create your style
    ...
    XWPFStyle style = new XWPFStyle(ctStyle);

    style.setType(STStyleType.PARAGRAPH);
    styles.addStyle(style);
}