2013-02-05 75 views
3

我有一个文档模板,其中一些字段是静态的,而其他字段是动态的。我需要替换一些数据(名称,姓氏,薪水)并生成新文件。你建议要做什么库? POI是否合适? 我正在使用Spring,Java EE6和Oracle。如何使用Java从模板或现有文档创建Word文档?

+0

看看这个问题:http://stackoverflow.com/questions/10005678/learning-apache-poi –

回答

3

您可以尝试Apache POI,但POI的操作字文件所需的HWPF和XWPF部分实际上非常复杂 - 您需要至少理解字文件的结构!利用iText和PDF

解决方案我就与PDF类似的东西(这可能是一个选择)

1)可以使用的LibreOffice文档中创建字段(如在Acrobat临)

  • 创建的.odt文件和风格它
  • 或使用MS Word或LibreOffice的作家你的模板转换成它
  • 然后去查看 - > Toolsbars - >表单设计和设置“设计模式开/关”
  • 现在你可以将字段添加到您的文件(双击它会打开字段属性)
  • 当你完成: “文件 - >导出为PDF”

2)现在你可以使用的iText填写创建领域

下面就是示例代码:

public byte[] getDocumentAsByteArray(Object dataBean, String pdfTemplateName) throws KkmsException { 

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
    PdfStamper stamp = null; 
    InputStream templateInputStream = null; 

    Locale local = new Locale(language); 

    try { 
     templateInputStream = // get the file input stream of the pdf 
     PdfReader reader = new PdfReader(templateInputStream); 

     // Create a stamper that will copy the document to a new file 
     stamp = new PdfStamper(reader, outputStream); 

     AcroFields form = stamp.getAcroFields(); 

     // form fields are normal text in the end 
     stamp.setFormFlattening(true); 
     Map<String, AcroFields.Item> map = (Map<String, AcroFields.Item>)form.getFields(); 
     if (map != null) { 
      if (map.size() == 0) { 
       logger.debug("There are no fields in this PDF layout"); 
      } 
      for (Entry<String, AcroFields.Item> e : map.entrySet()) { 
       logger.debug("PDF fieldname = " + e.getKey()); 

       // at the moment we only handle text fields 
       if (AcroFields.FIELD_TYPE_TEXT == form.getFieldType(e.getKey())) { 
        fillForm(dataBean, form, e.getKey(), local); 
       } else { 
        logger.warn("Field type is not supported: "+form.getFieldType(e.getKey())); 
       } 
      } 
     } 

     stamp.close(); 
    } catch (Exception e) { 
     logger.warn("Failed to create PDF document", e); 
     throw new KkmsException("Failed to create PDF document: "+e.getMessage()); 
    } finally { 
     if (templateInputStream != null) { 
      try { 
       templateInputStream.close(); 
      } catch (IOException e) { 
       throw new KkmsException("Failed to close InputStream of PDF document", e); 
      } 
     } 
    } 
    return outputStream.toByteArray(); 
} 

最后你得到一个PDF - >希望这可以帮助你至少一点点!

另一种快速和肮脏的解决方案

可能是使用的ODT电源或DOCX - >转换您的文件到DOCX或ODT - >它只是一个zip文件 - >所以把它解压 - >你会看到的content.xml文件的zip的根 - >有在那里 的所有文件内容现在,你可以添加一些神奇的标签(例如$$$)在这里其可之后你的程序来代替

<text:p text:style-name="P3">SAP Customer Number:</text:p> 

<text:p text:style-name="P3">SAP Customer Number: $$$sapCustomerNumber$$$</text:p> 

现在创建一个解压缩odt/docx文件的程序 - >替换标签 - >再次压缩文件

2

These slides,从我在OSDC 2012发表的演讲中,概述了一些主要方法。

这些天我可能会添加“生成你想要的XHTML,然后将其导出到docx”。由于我们引入了docx4j-ImportXHTML,并支持将CSS @class值转换为Word样式,因此我们越来越多地看到了这种方法。