1

我需要从新的 Office 文件(.docx、.xlsx)中读取文件详细信息,尤其是作者、标题、主题。我从 MS 中找到了这篇文章,其中也有一些方法 - http://msdn.microsoft.com/en-us/library/bb739835%28v=office.12%29.aspx 但我似乎可以完成这项工作。我使用的方法是:

public static string WDRetrieveCoreProperty(string docName, string propertyName)
{
   // Given a document name and a core property, retrieve the value of the property.
   // Note that because this code uses the SelectSingleNode method, 
   // the search is case sensitive. That is, looking for "Author" is not 
   // the same as looking for "author".

   const string corePropertiesSchema = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
   const string dcPropertiesSchema = "http://purl.org/dc/elements/1.1/";
   const string dcTermsPropertiesSchema = "http://purl.org/dc/terms/";

   string propertyValue = string.Empty;

   using (WordprocessingDocument wdPackage = WordprocessingDocument.Open(docName, true))
   {
      // Get the core properties part (core.xml).
      CoreFilePropertiesPart corePropertiesPart = wdPackage.CoreFilePropertiesPart;

      // Manage namespaces to perform XML XPath queries.
      NameTable nt = new NameTable();
      XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
      nsManager.AddNamespace("cp", corePropertiesSchema);
      nsManager.AddNamespace("dc", dcPropertiesSchema);
      nsManager.AddNamespace("dcterms", dcTermsPropertiesSchema);

      // Get the properties from the package.
      XmlDocument xdoc = new XmlDocument(nt);

      // Load the XML in the part into an XmlDocument instance.
      xdoc.Load(corePropertiesPart.GetStream());

      string searchString = string.Format("//cp:coreProperties/{0}", propertyName);

      XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager);
      if (!(xNode == null))
      {
         propertyValue = xNode.InnerText;
      }
   }

   return propertyValue;
}

所以我把这个方法称为:

WDRetrieveCoreProperty(textBox1.Text, "Authors"); 
// textBox1 has path to some .docx file

但它总是返回 null。那么这有什么问题呢?

4

2 回答 2

2

我知道这个问题很老,但是在研究同一问题时遇到了它。MSDN 上的示例有检索核心属性的方法的示例代码,但没有使用该方法的示例。

传递属性以查找时,您必须包含命名空间前缀。因此,使用 OP 方法访问 lastModifiedBy 核心属性如下所示:

WDRetrieveCoreProperty(textBox1.Text, "cp:lastModifiedBy");
于 2013-08-26T19:32:38.713 回答
1

我做了这个...

using System.IO.Packaging; // Assembly WindowsBase.dll
  :
     static void Main(string[] args)
     {
        String path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        String file = Path.Combine(path, "Doc1.docx");

        Package docx = Package.Open(file, FileMode.Open, FileAccess.Read);
        String subject = docx.PackageProperties.Subject;
        String title = docx.PackageProperties.Title;
        docx.Close();
     }
于 2011-10-24T14:18:37.240 回答