【问题标题】:how to update metadata of docx file using apache poi in java?如何在 java 中使用 apache poi 更新 docx 文件的元数据?
【发布时间】:2013-11-06 10:36:34
【问题描述】:

我不知道如何使用 apache poi 更新 docx 文件的元数据(标题、主题、作者等)。 我已经尝试过使用 apache poi 的 doc 文件:


     File poiFilesystem = new File(file_path1);

     /* Open the POI filesystem. */
     InputStream is = new FileInputStream(poiFilesystem);
    POIFSFileSystem poifs = new POIFSFileSystem(is);
     is.close();

     /* Read the summary information. */
     DirectoryEntry dir = poifs.getRoot();
     SummaryInformation si;
     try
     {
        DocumentEntry siEntry = (DocumentEntry)
             dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
         DocumentInputStream dis = new DocumentInputStream(siEntry);
         PropertySet ps = new PropertySet(dis);
         dis.close();
         si = new SummaryInformation(ps);
     }
     catch (FileNotFoundException ex)
     {
         /* There is no summary information yet. We have to create a new
         * one. */
         si = PropertySetFactory.newSummaryInformation();
     }


     si.setAuthor("xzy");
     System.out.println("Author changed to " + si.getAuthor() + ".");
    si.setSubject("mysubject");
    si.setTitle("mytitle");

【问题讨论】:

  • 我的问题没有得到任何答复......
  • 你想更新什么样的元数据?
  • 喜欢作者、标题等......
  • 嗨 Michael Kazarian 希望你现在得到我的问题...
  • 您的问题/答案对我帮助很大。我只想提一下,对于像 HWPFDocument doc 这样的自创文件,调用 doc.getSummaryInformation() 会直接为您提供 SummaryInformation。

标签: java apache-poi


【解决方案1】:

下面使用POI-3.10。您可以使用PackageProperties 设置一些元数据:

import java.util.Date;
import org.apache.poi.openxml4j.opc.*;
import org.apache.poi.openxml4j.util.Nullable;

class SetDOCXMetadata{
  public static void main(String[] args){
      try{
          OPCPackage opc = OPCPackage.open("metadata.docx");
          PackageProperties pp = opc.getPackageProperties();

          Nullable<String> foo = pp.getLastModifiedByProperty();
          System.out.println(foo.hasValue()?foo.getValue():"empty");
          //Set some properties
          pp.setCreatorProperty("M Kazarian");
          pp.setLastModifiedByProperty("M Kazarian " + System.currentTimeMillis());
          pp.setModifiedProperty(new Nullable<Date>(new Date()));
          pp.setTitleProperty("M Kazarian document");

          opc.close();
      } catch (Exception e) {}
  }
}

【讨论】:

  • 如果您创建文档而不是打开它:对于从 POIXMLDocument 继承的 XWPFDocument 和其他类,getProperties().getCoreProperties() 为您提供了一个 CoreProperties 实例,您也可以在其中更改所有这些属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
  • 2015-11-23
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多