目次

Outlookの予定表から予定を取得する

Outlookの予定表にある予定をプログラムから取得する方法を紹介します。

準備

Visual Studio 2010でWinformアプリケーションを新規作成します。ソリューションエクスプローラで[参照設定]ノードを選択し右クリックでポップアップメニューを表示します。ポップアップメニューの[参照の追加]メニューをクリックします。


[参照の追加]ダイアログボックスが表示されます。[.NET]タブを選択し"Microsoft.Office.Interop.Outlook"コンポーネントを選択します。下図の例ではバージョン"14"とバージョン"12"がありますが、バージョン12は.NETの乱値無のv1.1用のため、バージョン"14"を用います。選択後[OK]ボタンをクリックします。

コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Outlook;

namespace OutlookAccess
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      Microsoft.Office.Interop.Outlook.Application outlook
        = new Microsoft.Office.Interop.Outlook.Application();
      NameSpace ns = outlook.GetNamespace("MAPI");
      MAPIFolder oFolder = ns.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
      textBox1.Text += oFolder.Name+"\r\n";

      Items oItems = oFolder.Items;
      AppointmentItem oAppoint = oItems.GetFirst();
      while (oAppoint != null) {
        textBox1.Text += oAppoint.Subject + "\r\n";
        textBox1.Text += oAppoint.Start.ToString("yyyy/MM/dd hh:mm:ss")+ "\r\n";
        textBox1.Text += oAppoint.End.ToString("yyyy/MM/dd hh:mm:ss") + "\r\n";
        textBox1.Text += "---\r\n";

        oAppoint = oItems.GetNext();
      }
    }
  }
}

解説

Microsoft.Office.Interop.Outlook名前空間を参照可能にします。
 using Microsoft.Office.Interop.Outlook;

Outlookアプリケーションを新規作成します。
 Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();

Outlookの名前空間を取得します。現在のところサポートしている名前空間は"MAPI"のみですので、引数には"MAPI"を指定します。
 NameSpace ns = outlook.GetNamespace("MAPI");

MAPIFolderを取得します。今回は標準のフォルダを取得するのでGetDefaultFolder()メソッドを使います。取得するフォルダはスケジュールのフォルダですので引数にOlDefaultFolders.olFolderCalendarを与えます。
 MAPIFolder oFolder = ns.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);

フォルダ名をテキストボックスに表示します。
 textBox1.Text += oFolder.Name+"\r\n";

GetFirst()メソッドを用いて、フォルダにある最初の要素を取得します。スケジュールのフォルダですので、取り出される要素はAppointmentItemになります。
 AppointmentItem oAppoint = oItems.GetFirst();

アイテムの内容をテキストボックスに表示します。今回は予定名と開始時間と終了時間をテキストボックスに表示します。要素を表示したのちGetNext()メソッドを用いて次の要素を取得します。要素がnullになるまで繰り返すことですべての予定表にあるすべての予定を取得できます。
 while (oAppoint != null) {
   textBox1.Text += oAppoint.Subject + "\r\n";
   textBox1.Text += oAppoint.Start.ToString("yyyy/MM/dd hh:mm:ss")+ "\r\n";
   textBox1.Text += oAppoint.End.ToString("yyyy/MM/dd hh:mm:ss") + "\r\n";
   textBox1.Text += "---\r\n";
 
   oAppoint = oItems.GetNext();
 }

実行結果

button1をクリックするとOutlookの予定表から予定を取得して表示します。


Outlookの予定表は下図の状態になっています。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
作成日: 2011-06-28
Copyright © iPentec all rights reserverd.