スプレッドシート ドキュメント内のすべての名前付き範囲のディクショナリを取得する
このトピックでは、Open XML SDK for Office のクラスを使用して、Microsoft Excel ブックで定義されているすべての名前の名前と範囲を含むディクショナリをプログラムで取得する方法について説明します。 このトピックでは、この作業を説明するために GetDefinedNames メソッドの例を示します。
GetDefinedNames メソッド
GetDefinedNames メソッドは、定義された名前を取得するドキュメントの名前を示す 1 つのパラメーターを受け取ります。 メソッドは、指定したブック内の定義された名前に関する情報を含む Dictionary<TKey,TValue> インスタンスを返します。定義された名前がない場合は空になる可能性があります。
コードの動作のしくみ
コードは Open メソッドを 使用してスプレッドシート ドキュメントを開き、最後の false パラメーターを使用してドキュメントを読み取り専用で開く必要があることを示します。 開いているブックの場合、コードでは WorkbookPart プロパティを使用してメインブック パーツに移動します。 コードは、この参照を wbPart という名前の変数に保存します。
// Open the spreadsheet document for read-only access.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
{
// Retrieve a reference to the workbook part.
var wbPart = document.WorkbookPart;
定義名を取得する
ブック パーツを取得したら、次の手順は単純です。 このコードでは、ブック パーツの Workbook プロパティを使用してブックのコンテンツへの参照を取得し、Open XML SDK によって提供される DefinedNames コレクションを取得します。 このプロパティは、ブックに含まれるすべての定義名のコレクションを返します。 プロパティが null 以外の値を返す場合、コードはコレクションを反復処理し、各名前付きパーツに関する情報を取得し、定義された各名前のディクショナリにキー名と値 (範囲の説明) を追加します。
// Retrieve a reference to the defined names collection.
DefinedNames? definedNames = wbPart?.Workbook?.DefinedNames;
// If there are defined names, add them to the dictionary.
if (definedNames is not null)
{
foreach (DefinedName dn in definedNames)
{
if (dn?.Name?.Value is not null && dn?.Text is not null)
{
returnValue.Add(dn.Name.Value, dn.Text);
}
}
}
サンプル コード
以下に、C# と Visual Basic の完全な GetDefinedNames コード サンプルを示します。
static Dictionary<String, String>GetDefinedNames(String fileName)
{
// Given a workbook name, return a dictionary of defined names.
// The pairs include the range name and a string representing the range.
var returnValue = new Dictionary<String, String>();
// Open the spreadsheet document for read-only access.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
{
// Retrieve a reference to the workbook part.
var wbPart = document.WorkbookPart;
// Retrieve a reference to the defined names collection.
DefinedNames? definedNames = wbPart?.Workbook?.DefinedNames;
// If there are defined names, add them to the dictionary.
if (definedNames is not null)
{
foreach (DefinedName dn in definedNames)
{
if (dn?.Name?.Value is not null && dn?.Text is not null)
{
returnValue.Add(dn.Name.Value, dn.Text);
}
}
}
}
return returnValue;
}