2013-02-05 71 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樣式,因此我們越來越多地看到了這種方法。