メソッドに貼り付けるだけで機能するソースコードを多数用意しています。
セルの値を取得/設定する
指定したセルの値を取得/設定します。
以下の処理は、行列番号でセルを指定し、そのセルに任意の値を設定し、入力された値を取得しています。
// Excel操作用オブジェクト
Microsoft.Office.Interop.Excel.Application xlApp = null;
Microsoft.Office.Interop.Excel.Workbooks xlBooks = null;
Microsoft.Office.Interop.Excel.Workbook xlBook = null;
Microsoft.Office.Interop.Excel.Sheets xlSheets = null;
Microsoft.Office.Interop.Excel.Worksheet xlSheet = null;
// Excelアプリケーション生成
xlApp = new Microsoft.Office.Interop.Excel.Application();
// 既存のBookを開く
xlBooks = xlApp.Workbooks;
xlBook = xlBooks.Open(System.IO.Path.GetFullPath(@"..\..\..\data\work01.xlsx"));
// シートを選択する
xlSheets = xlBook.Worksheets;
// 1シート目を操作対象に設定する
// ※Worksheets[n]はオブジェクト型を返すため、Worksheet型にキャスト
xlSheet = xlSheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
// 表示
xlApp.Visible = true;
// セルのオブジェクト
Microsoft.Office.Interop.Excel.Range xlRange = null;
Microsoft.Office.Interop.Excel.Range xlCells = null;
// B3セルを指定
xlCells = xlSheet.Cells;
xlRange = xlCells[3, 2] as Microsoft.Office.Interop.Excel.Range;
// ◆現在の値を表示◆
MessageBox.Show(xlRange.Value);
// ◆値を設定◆
xlRange.Value = "変更後の値";
// 変更後の値を表示
MessageBox.Show(xlRange.Value);
// ■■■以下、COMオブジェクトの解放■■■
// cell解放
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlRange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlCells);
// Sheet解放
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheets);
// Book解放
//xlBook.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBooks);
// Excelアプリケーションを解放
//xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);