- Office2003プライマリ相互運用機能アセンブリをコンピュータにダウンロードしてインストールします
- Visual Studioプロジェクトを作成し、GACから「Microsoft.Office.Interop.Excel.dll」への参照を追加します。
- これで、このコードを記述して、任意のExcelfileからデータを読み取ることができます。
例:
using Excel = Microsoft.Office.Interop.Excel;
string pathOfExcelFile = "C:\\MyDataFile.xls";
Excel.Application excelApp = new Excel.Application();
excelApp.DisplayAlerts = false; //Don't want Excel to display error messageboxes
Excel.Workbook workbook = excelApp.Workbooks.Open(pathOfExcelFile, 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); //This opens the file
Excel.Worksheet sheet = workbook.get_Item(1); //Get the first sheet in the file
Excel.Range bColumn = sheet.get_Range("B", null);
List<string> dataItems = new List<string>();
foreach (object o in bColumn)
{
Excel.Range row = o as Excel.Range;
string s = row.get_Value(null);
dataItems.Add(s);
}