Excelを読む

環境は、Visual C# 2010 Express の Microsoft Office (Excel) 2007。

Microsoft Excel Object Library を追加する。

ソリューションエクスプローラから、参照設定を右クリックし、参照の追加をクリックする。
COMタブを選択し、Microsoft Excel 12.0 Object Libraryを選択してOKを押す。

プロジェクトの参照設定に

が追加される。

Book1.xlsx

A B C
1 ほげ
2 ふが
3 ぴよ

コード

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Excel.Application xlsx = new Excel.Application();
            Excel.Workbook book = null;
            try
            {
                string fileName =
                    System.IO.Directory.GetCurrentDirectory()
                    + "\\Book1.xlsx";   // 絶対パスじゃないとダメみたい

                xlsx = new Excel.Application();
                book = (Excel.Workbook)xlsx.Workbooks.Open(
                    fileName,
                    Type.Missing,
                    true,			// ReadOnly
                    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.Worksheet sheet = (Excel.Worksheet)book.Sheets[1];

                string hoge = (string)((Excel.Range)sheet.Cells[1, 1]).Text;
                Console.WriteLine(hoge);

                string fuga = (string)((Excel.Range)sheet.Cells[2, 2]).Text;
                Console.WriteLine(fuga);

                string piyo = (string)((Excel.Range)sheet.Cells[3, 3]).Text;
                Console.WriteLine(piyo);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.GetType().FullName + " occured!");
            }
            finally
            {
                /* ファイルが開けなかったりすると
                 * System.Runtime.InteropServices.COMException が発生し、
                 * bookやxlsxを閉じないと、タスクマネージャにEXCELのプロセスが
                 * 残りっぱなしになってしまうので注意。
                 */
                if (book != null)
                {
                    book.Close(Type.Missing, Type.Missing, Type.Missing);
                }
                xlsx.Quit();
            }
        }
    }
}

C++でこれぐらい簡単に開ける方法探し中…。