2017-07-28 39 views
0

我正嘗試使用apache-poi在單詞(.docx)文檔中創建標題標題。使用標題的自定義樣式的Apache POI Word

我有一個模板,其中只包含自定義樣式以及使用自定義樣式的標題標題示例。

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

我的自定義風格被稱爲「CUSTOM_YNP」(我直接在Word中創建它),但是當我使用下面的行,則返回false

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

,當然,當我嘗試使用這種風格,這是行不通的,實際上它打印我的字符串中的「正常」的風格

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

只是爲了記錄在案,我的「保存文件」行:

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

我已經閱讀了這個問題,但實際上並不能找到一個解決我的問題...... How can I use predefined formats in DOCX with POI?

編輯:它的工作原理,如果我創建使用Apache的POI我自己的風格....不過我woudl真的很喜歡使用Word文檔中的現有樣式。

回答

2

一個*.docxZIP存檔。您可以解壓縮並查看/word/styles.xml。在那裏你會看到沒有下劃線的w:styleId="CUSTOMYNP"。名稱是「CUSTOM_YNP」<w:name w:val="CUSTOM_YNP"/>。所以:

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(); 
+0

就是這樣! 「真實」樣式名稱可能與Word中「顯示」樣式名稱不同。另外,我注意到我不需要在我的模板中使用我的樣式,這是件好事。 – IronRabbit

1

請務必先創建樣式,並把它添加到您的文檔:

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

隨着addCustomHeadingStyle之中:

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); 
} 
+0

謝謝,但我要的是使用現有的風格,已經在我的範本.docx ...這可能嗎? – IronRabbit

+0

你是否確定docx文件包含Style? docx文件是否包含任何文本? _似乎從文檔中丟棄了未使用的樣式。您需要使用這些Styles_在文檔中擁有現有的文字。 –