Excelファイルを読み込み、セルの値を取得し表示する - C#

C#でExcelファイルを読み込み、セルの値を取得して、画面に表示する手順とコードを紹介します。

概要

Microsoft.Office.Interop.Excel アセンブリを利用して、Excelファイルを読み込みセルの値を表示します。
メモ
OpenXML SDKを利用してExcelファイルを読み込む方法はこちらの記事を参照してください。

事前準備: Microsoft.Office.Interop.Excel アセンブリの参照

Visual Studio を起動し、Windows Formアプリケーション(.NET Framework)を作成します。 プロジェクトの作成後、 Microsoft.Office.Interop.Excel アセンブリの参照を追加します。 参照の追加の手順はこちらの記事を参照してください。

事前準備: Excelファイルの準備

Excelファイルを作成します。今回はA1セルに値を入力して保存します。

プログラム

UI

Windows Formアプリケーションを作成し、下図のフォームを作成します。
Button, MultiLineプロパティをtrueに設定したTextBox, OpenFileDialogを配置します。

コード

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

namespace ExcelFileRead
{
  public partial class FormSimpleRead : Form
  {
    public FormSimpleRead()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      if (openFileDialog1.ShowDialog() == DialogResult.OK) {
        Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
        ExcelApp.Visible = false;
        Workbook wb = ExcelApp.Workbooks.Open(openFileDialog1.FileName,
          Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
          Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
          Type.Missing);

        Worksheet ws1 = wb.Sheets[1];
        ws1.Select(Type.Missing);
        Range range = ExcelApp.get_Range("A1", Type.Missing);
        if (range != null) {
          var val = range.Value2;
          textBox1.Text += Convert.ToString(val);
        }

        wb.Close(false, Type.Missing, Type.Missing);
        ExcelApp.Quit();

      }

    }
  }
}

解説

下記のコードで、Microsoft.Office.Interop.Excelをusingします。
using Microsoft.Office.Interop.Excel;

Excelアプリケーションオブジェクトを新規作成します。Windows Formアプリケーションの場合はSystem.Windows.Froms.Applicationと名前が競合するため完全名で指定します。
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();

Excelアプリケーションの表示設定を変更します。VisibleをTrueに設定した場合はExcelアプリケーションの画面が表示されます。 今回はExcelアプリケーションを画面に表示させる必要がないためFalseに設定します。
ExcelApp.Visible = false;

ワークブック(Microsoft Excel ワークシートファイル)を開きます。
  Workbook wb = ExcelApp.Workbooks.Open(openFileDialog1.FileName,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
    Type.Missing);

先の処理で開いたワークブックのシートの1枚目のオブジェクトをws1に代入し、このシートを選択します。
  Worksheet ws1 = wb.Sheets[1];
  ws1.Select(Type.Missing);

下記のコードで範囲を取得します。今回はA1セルを範囲として取得します。
  Range range = ExcelApp.get_Range("A1", Type.Missing);

選択範囲がnullでなければ選択範囲は有効ですので、選択部分(今回はA1セル)の値を取得します。 値はdynamic型で取り出せますので、dynamicもしくはvar(バリアント型)で受け取ります。受け取った値をtextBox2に表示します。
  if (range != null) {
    var val = range.Value2;
    textBox1.Text += Convert.ToString(val);
  }

ワークブックを閉じ、Excelアプリケーションを終了します。
  wb.Close(false, Type.Missing, Type.Missing);
  ExcelApp.Quit();

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[button1]をクリックします。下図のファイルを開くダイアログが表示されます。事前に作成したExcelファイルを選択して開きます。


ExcelシートのA1セルの値を読み取りテキストボックスに表示します。ExcelのA1セルの値が読みだされ、テキストボックスに表示されていることが確認できます。

プログラム : 確実にオブジェクトを開放する場合

先のコードの場合、アプリケーションが終了するとExcelアプリケーションも終了します。 バッチ処理のプログラムや数回程度しか処理を実行しない場合は、先のコードでも大きな問題は発生しませんが、繰り返し処理を実行する場合には、 メモリリークをを防ぐためにも、Excelアプリケーションや他のオブジェクトを確実に開放する必要があります。
オブジェクトの開放処理のコードを記述したコードを以下に紹介します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace ExcelFileRead
{
  public partial class FormSimpleRead : Form
  {
    public FormSimpleRead()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      if (openFileDialog1.ShowDialog() == DialogResult.OK) {
        Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
        ExcelApp.Visible = false;
        Workbook wb = ExcelApp.Workbooks.Open(openFileDialog1.FileName,
          Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
          Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
          Type.Missing);

        Worksheet ws1 = wb.Sheets[1];
        ws1.Select(Type.Missing);
        Range range = ExcelApp.get_Range("A1", Type.Missing);
        if (range != null) {
          var val = range.Value2;
          textBox1.Text += Convert.ToString(val);
        }
        
        wb.Close(false, Type.Missing, Type.Missing);

        System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
        range = null;
        System.Runtime.InteropServices.Marshal.ReleaseComObject(ws1);
        ws1 = null;
        System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
        wb = null;
        System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp.Workbooks);

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        ExcelApp.Quit();

        System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);
        ExcelApp = null;

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
       

      }

    }
  }
}

解説

プログラム内で利用した、RangeオブジェクトやWorksheet,WorkbookオブジェクトをReleaseComObject()を呼び出して開放します。 変数にオブジェクトを代入していた場合は、解放後に変数にnullを代入し、変数から参照されていない状態にします。
  System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
  range = null;
  System.Runtime.InteropServices.Marshal.ReleaseComObject(ws1);
  ws1 = null;
  System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
  wb = null;
  System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp.Workbooks);

GC.Collectメソッドを呼び出し、強制的にガベージコレクションを実行します。
  GC.Collect();
  GC.WaitForPendingFinalizers();
  GC.Collect();

Excelアプリケーションを終了し、ReleaseComObjectメソッドでExcelアプリケーションを開放します。解放後には変数にnullを代入し参照されない状態にします。 その後、GC.Collectメソッドを呼び出し、強制的にガベージコレクションを実行します。
  ExcelApp.Quit();

  System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);
  ExcelApp = null;

  GC.Collect();
  GC.WaitForPendingFinalizers();
  GC.Collect();
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-04-13
改訂日: 2024-04-13
作成日: 2011-01-04
iPentec all rights reserverd.