1

我的要求是我应该读取一个模板文件并更改其内容中的一些值并将其写回另一个文件。最重要的是,它应该具有与模板相同的样式。

我面临的问题是我能够读写,但也很难转移风格。特别是我厌倦了尝试将段落样式应用于文档。请帮助我.....这是我的代码

  public static void main(String[] args) {
    try {
          HWPFDocument templateFile = new HWPFDocument(new FileInputStream("D:\\POI\\testPOIin.doc"));
          HWPFDocument blankFile = new HWPFDocument(new FileInputStream("D:\\POI\\blank.doc"));

        ParagraphProperties pp = templateFile.getRange().getParagraph(4).cloneProperties();
        blankFile.getRange().insertAfter(pp, 0);
        OutputStream out = new FileOutputStream("D:\\POI\\testPOIout.doc");
        blankFile.write(out);

      } catch (FileNotFoundException fnfe) {
          // TODO: Add catch code
          fnfe.printStackTrace();
      } catch (Exception ioe) {
          // TODO: Add catch code
          ioe.printStackTrace();
      }
  }
}

请让我知道我做错了.....

4

1 回答 1

0

我也有类似的任务,经过调查,我创建了解决方案,但它仅适用于 docx 文件:

public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream(new File("transformed.docx"));
    XWPFDocument doc = new XWPFDocument(new FileInputStream(new File("original.docx")));
    for(XWPFParagraph p:doc.getParagraphs()){
        for(XWPFRun r:p.getRuns()){
            for(CTText ct:r.getCTR().getTList()){
                String str = ct.getStringValue();
                if(str.contains("NAME")){
                    str = str.replace("NAME", "Java Dev");
                    ct.setStringValue(str);
                }
            }
        }
    }
    doc.write(fos);
}

它对低级元素进行操作,因此可以保存样式和其他道具。希望它会帮助某人。

于 2012-10-18T12:58:54.300 回答