代码之家  ›  专栏  ›  技术社区  ›  IronRabbit

Apache POI Word使用自定义标题样式

  •  2
  • IronRabbit  · 技术社区  · 8 年前

    我有一个模板,其中只包含自定义样式和标题使用自定义样式的例子。

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

    我的自定义样式称为“custom\u 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创建自己的样式,它会起作用……不过我还是很喜欢使用word文档中的现有样式。

    2 回复  |  直到 8 年前
        1
  •  3
  •   Axel Richter    8 年前

    A. *.docx 是一个 ZIP /word/styles.xml .在那里你会看到 w:styleId="CUSTOMYNP" <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();
    
        2
  •  1
  •   Mathias G.    8 年前

    确保首先创建样式并将其添加到文档中:

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

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