ワープロ ドキュメントからアプリケーション プロパティ値を取得する
このトピックでは、Open XML SDK for Office のクラスを使用して、ドキュメントをWordに読み込まずに、Microsoft Word ドキュメントからアプリケーション プロパティをプログラムで取得する方法について説明します。 この作業を説明するために、コードの例を示します。
アプリケーション プロパティの取得
アプリケーション ドキュメントのプロパティを取得するには、WordprocessingDocument オブジェクトのExtendedFilePropertiesPart プロパティを取得し、必要な特定のアプリケーション プロパティを取得します。 これを行うには、まず、次のコードに示すように、ドキュメントへの参照を取得する必要があります。
using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, false))
{
WordprocessingDocument オブジェクトへの参照を指定すると、ドキュメントの ExtendedFilePropertiesPart プロパティへの参照を取得できます。 このオブジェクトは独自のプロパティを提供し、それぞれがアプリケーション ドキュメントのプロパティのいずれかを表します。
if (document.ExtendedFilePropertiesPart is null)
{
throw new ArgumentNullException("ExtendedFilePropertiesPart is null.");
}
var props = document.ExtendedFilePropertiesPart.Properties;
ExtendedFilePropertiesPartのプロパティへの参照を取得したら、次の例に示すような単純なコードを使用して、任意のアプリケーション プロパティを取得できます。 コードでは、Text
プロパティを取得する前に、各プロパティへの参照がNothing
null
されていないことを確認する必要があることに注意してください。 コア プロパティとは異なり、ユーザー (またはアプリケーション) が特に値を設定していない場合には、ドキュメント プロパティは取得できません。
if (props.Company is not null)
Console.WriteLine("Company = " + props.Company.Text);
if (props.Lines is not null)
Console.WriteLine("Lines = " + props.Lines.Text);
if (props.Manager is not null)
Console.WriteLine("Manager = " + props.Manager.Text);
サンプル コード
以下に、C# と Visual Basic の完全なコード サンプルを示します。
using DocumentFormat.OpenXml.Packaging;
using System;
static void GetApplicationProperty(string fileName)
{
using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, false))
{
if (document.ExtendedFilePropertiesPart is null)
{
throw new ArgumentNullException("ExtendedFilePropertiesPart is null.");
}
var props = document.ExtendedFilePropertiesPart.Properties;
if (props.Company is not null)
Console.WriteLine("Company = " + props.Company.Text);
if (props.Lines is not null)
Console.WriteLine("Lines = " + props.Lines.Text);
if (props.Manager is not null)
Console.WriteLine("Manager = " + props.Manager.Text);
}
}