Microsoft Office 2007 Code Snippetsの紹介

前回のブログ(VSUG Day & SharePouint Forumデモファイル)で紹介したスニペットについてお話します。

Open XMLファイルを.NET Frameworkで操作する場合、現在のところ、System.IO.Packaging APIか、あるいは、Open XML Format SDK を使用する必要があります。

System.IO.Packaging APIを使用する場合、ファイルを細かく制御することができるのですが、やはりコード量は多くなる傾向にあるでしょう。
しかし、OpenXMLファイルの操作という点にプログラムを絞れば、ある程度定型化することが可能であるはずです。
その視点で作成されたのが以下のリンクにあるコードスニペットです。

2007 Office System Sample: Open XML File Format Code Snippets for Visual Studio 2005
https://go.microsoft.com/fwlink/?LinkID=106943

Visual Studio 2005とありますが、Visual Studio 2008使用することも十分可能です。

ちょっとやってみましょう。

上記をインストール後、Visual Studio のコードスニペットマネージャーから、Open XML File Formatフォルダをインポートします。このフォルダは、上記を仮に、C:\Users\Administrator\Documents\Visual Studio 2008\Code Snippetsにインストールした場合、C:\Users\Administrator\Documents\Visual Studio 2008\Code Snippets\Visual C#\Open XML File Formatとなります。

image

ソースコードの適当な場所で、スニペットの挿入を行います。
Open XML File Formatを選択します。

image

このOpen XML File Format内部には以下のように定型的な処理が含まれていますので、適当な処理を選択します。

image

前回のデモで行ったのは、「How to : Get To the Document Part」です。

指定したファイルのドキュメントパーツを取得することが可能です。
これを選択すると以下のような関数が挿入されます。

public void GetToDocPart(string fileName)
{
    // Given a file name, retrieve the officeDocument part.

    const string documentRelationshipType = "https://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";

    //  Open the package with read/write access.
    using (Package myPackage = Package.Open(fileName, FileMode.Open, FileAccess.ReadWrite))
    {
        //  Get the main document part (workbook.xml, document.xml, presentation.xml).
        foreach (System.IO.Packaging.PackageRelationship relationship in myPackage.GetRelationshipsByType(documentRelationshipType))
        {
            //  There should only be one document part in the package.
            Uri documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
            PackagePart documentPart = myPackage.GetPart(documentUri);

            XmlDocument doc = new XmlDocument();
            doc.Load(documentPart.GetStream());

            //  =============================
            //  Your code, which works with the document part, goes here.
            //  =============================
            MessageBox.Show(doc.InnerXml);

            //  Save the modified document back into its part. Not necessary
            //  unless you make changes to the document.
            doc.Save(documentPart.GetStream(FileMode.Create, FileAccess.Write));

            //  Only one document part, so get out now.
            break;
        }
    }

System.IO.Packaging APIを使用する場合、windowsbaseの参照設定が必要になります。
加えて以下をusingしておくと便利でしょう。

using System.IO.Packaging;
using System.Xml;
using System.IO;

後は、上記の関数を呼び出すだけです。

private void button1_Click(object sender, EventArgs e)
{
    GetToDocPart(@"C:\demo.docx");
}

このまま実行しても、単にメッセージとして、ドキュメントパーツのXMLが表示されるだけですので、追記された関数の内部は必要に応じて改編してください。