kurukuru-papaのブログ

主に、ソフトウェア開発に関連したメモを書き溜めたいと思います。

Excelファイル読み込み方法(事前バインディング方式)

Visual C#にて、Excelファイルを読み込む処理を書いてみました。

ここでは、事前バインディング方式と呼ばれる方法を使っています。この方法では、ExcelのVBAを使っているのと同じような感覚でプログラミングが出来ました。

ただし、開発時点で、ExcelアプリケーションのDLL(Microsoft Excel XXX Object Library。XXX部分はバージョン)へ参照設定を行ないます。このDLLは、Excelのバージョンによって異なるため、開発環境と、実行環境には、同じバージョンのExcelがインストールされている必要があります。

using System;
using Excel = Microsoft.Office.Interop.Excel;

    /// <summary>
    /// Excelファイルを読み込む
    /// </summary>
    /// <param name="path">Excelファイルパス</param>
    public override string ReadExcelFile(string path)
    {
        string result = "";
        Excel.Application app = null;

        try
        {
            // Excelアプリケーションを起動する
            app = new Excel.Application();

            // Excelファイルを開く
            Excel.Workbook book = app.Workbooks.Open(path,
                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, Type.Missing);

            // ファイル内容を読み込む
            Excel.Sheets sheets = book.Sheets;
            foreach (Excel.Worksheet sheet in sheets)
            {
                result += GetSheetContent(sheet);
            }
        }
        finally
        {
            if (app != null)
            {
                app.Quit();
            }
        }

        return result;
    }

    private string GetSheetContent(Excel.Worksheet sheet)
    {
        string result = "";

        result += "SheetName: " + sheet.Name + "\r\n";

        // 最終行、最終列を取得する。
        // Excelを編集中の場合、正しい値を読み込めない場合がある。
        Excel.Range lastCell = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
        int maxRow = lastCell.Row;
        int maxColumn = lastCell.Column;

        // シートの内容をCSV形式で文字列化する。
        for (int row = 1; row <= maxRow; row++)
        {
            string line = "";
            for (int column = 1; column <= maxColumn; column++)
            {
                // セルのインデックスは、1始まり。
                Excel.Range cell = (Excel.Range)sheet.Cells[row, column];

                if (column > 1)
                {
                    line += ", ";
                }
                line += cell.Text;
            }

            result += row + ": " + line + "\r\n";
        }

        return result;
    }

動作確認環境

  • OS : Windows 7
  • Excel : Version 2007
  • 開発環境 : Microsoft Visual C# 2008 Express Edition