2016-02-12 121 views
3

我想使用Apache POI將文件從* .fidus(Fidus Writer)平臺轉換爲* .docx格式,反之亦然。將自定義(擴展)屬性添加到docx和段落由Apache POI

在* .fidus文件中,我需要將它們作爲擴展或自定義屬性存儲在* .docx文件中,然後當我想將它們轉換回* .fidus時,可以檢索它們。

因此,我想知道如何使用POI類CustomProperties或類似的東西來添加一些屬性到docx文件。還有可能通過使用POI向docx文件中的段落添加自定義屬性(擴展屬性)?

在此先感謝。

回答

3

由於*.docx文件是基於XML的,我們必須使用POIXMLProperties.CustomProperties,請參閱http://poi.apache.org/apidocs/org/apache/poi/POIXMLProperties.CustomProperties.html

實施例:

import java.io.*; 
import org.apache.poi.*; 
import org.apache.poi.xwpf.usermodel.*; 

import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty; 

import java.util.GregorianCalendar; 

public class DocumentProperties { 

public static void main(String[] args) throws IOException { 

    XWPFDocument document = new XWPFDocument(new FileInputStream("This is a Test.docx")); 

    POIXMLProperties properties = document.getProperties(); 
    //http://poi.apache.org/apidocs/org/apache/poi/POIXMLProperties.html 

    //prints the core property Creator: 
    System.out.println(properties.getCoreProperties().getCreator()); 

    //prints the extendend property Application: 
    System.out.println(properties.getExtendedProperties().getApplication()); 

    //sets a custom property 
    POIXMLProperties.CustomProperties customproperties = properties.getCustomProperties(); 
    if (!customproperties.contains("Test")) { 
    customproperties.addProperty("Test", 123); 
    } 
    CTProperty ctproperty = customproperties.getProperty("Test"); 
    System.out.println(ctproperty); 
    System.out.println(ctproperty.getI4()); 

    //the above customproperties.addProperty() can only set boolean, double, integer or string properties 
    //the CTProperty contains more possibitities 
    if (!customproperties.contains("Test Date")) { 
    customproperties.addProperty("Test Date", 0); 
    ctproperty = customproperties.getProperty("Test Date"); 
    ctproperty.unsetI4(); 
    ctproperty.setFiletime(new GregorianCalendar(2016,1,13)); 
    } 
    ctproperty = customproperties.getProperty("Test Date"); 
    System.out.println(ctproperty); 
    System.out.println(ctproperty.getFiletime()); 


    FileOutputStream out = new FileOutputStream(new File("This is a Test.docx")); 
    document.write(out); 
} 
} 

POIXMLProperties.CustomProperties.addProperty()只能設定布爾,雙,整數或字符串的屬性,但底層CTProperty包含更多的可能性。

對於CTProperty參見http://grepcode.com/file/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/org/openxmlformats/schemas/officeDocument/x2006/customProperties/CTProperty.java#CTProperty