Visual C# を使用して Excel を自動化して配列を使用して範囲内のデータを入力または取得する方法
概要
この記事では、Microsoft Visual C# 2005 または Microsoft Visual C# .NET を使用して Microsoft Excel を自動化し、配列を使用して複数セル範囲の値を入力および取得する方法について説明します。
詳細情報
セルを 1 つずつ入力せずに複数セル範囲を塗りつぶすには、Range オブジェクトの Value プロパティを 2 次元配列に設定できます。 同様に、Value プロパティを使用して、複数のセルの値の 2 次元配列を一度に取得できます。 次の手順は、2 次元配列を使用したデータの設定と取得の両方に関するこのプロセスを示しています。
Microsoft Excel 用の Automation クライアントをビルドする
Microsoft Visual Studio 2005 または Microsoft Visual Studio .NET を起動します。
[ファイル] メニューの [新規] をクリックし、[プロジェクト] をクリックします。 Visual C# プロジェクトの種類から Windows アプリケーションを選択します。 Form1 は既定で作成されます。
Visual Studio 2005 の Microsoft Excel 11.0 オブジェクト ライブラリ または Visual Studio .NET の Microsoft Excel オブジェクト ライブラリへの参照を追加します。 これを行うには、次の手順を実行します。
- [ プロジェクト] メニューの [ 参照の追加] をクリックします。
- [COM] タブで、Microsoft Excel オブジェクト ライブラリを探し、[選択] をクリックします。
Visual Studio 2005 で、[COM] タブで Microsoft Excel 11.0 オブジェクト ライブラリを探します。
メモ Microsoft Office 2003 には、プライマリ相互運用機能アセンブリ (PIA) が含まれています。 Microsoft Office XP には PIA は含まれていませんが、ダウンロードできます。
[参照の追加] ダイアログ ボックスで [OK] をクリックして、選択内容を受け入れます。 選択したライブラリのラッパーを生成するように求められた場合は、[はい] をクリックします。
[表示] メニューの [ツールボックス] を選択し、ツールボックスを表示します。 Form1 に 2 つのボタンとチェック ボックスを追加します。
チェック ボックスの [名前] プロパティと [テキスト] プロパティを FillWithStrings に設定します。
Button1 をダブルクリックします。 フォームのコード ウィンドウが表示されます。
コード ウィンドウで、次のコードを置き換えます。
private void button1_Click(object sender, System.EventArgs e) { }
置換後:
//Declare these two variables globally so you can access them from both //Button1 and Button2. Excel.Application objApp; Excel._Workbook objBook; private void button1_Click(object sender, System.EventArgs e) { Excel.Workbooks objBooks; Excel.Sheets objSheets; Excel._Worksheet objSheet; Excel.Range range; try { // Instantiate Excel and start a new workbook. objApp = new Excel.Application(); objBooks = objApp.Workbooks; objBook = objBooks.Add( Missing.Value ); objSheets = objBook.Worksheets; objSheet = (Excel._Worksheet)objSheets.get_Item(1); //Get the range where the starting cell has the address //m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols. range = objSheet.get_Range("A1", Missing.Value); range = range.get_Resize(5, 5); if (this.FillWithStrings.Checked == false) { //Create an array. double[,] saRet = new double[5, 5]; //Fill the array. for (long iRow = 0; iRow < 5; iRow++) { for (long iCol = 0; iCol < 5; iCol++) { //Put a counter in the cell. saRet[iRow, iCol] = iRow * iCol; } } //Set the range value to the array. range.set_Value(Missing.Value, saRet ); } else { //Create an array. string[,] saRet = new string[5, 5]; //Fill the array. for (long iRow = 0; iRow < 5; iRow++) { for (long iCol = 0; iCol < 5; iCol++) { //Put the row and column address in the cell. saRet[iRow, iCol] = iRow.ToString() + "|" + iCol.ToString(); } } //Set the range value to the array. range.set_Value(Missing.Value, saRet ); } //Return control of Excel to the user. objApp.Visible = true; objApp.UserControl = true; } catch( Exception theException ) { String errorMessage; errorMessage = "Error: "; errorMessage = String.Concat( errorMessage, theException.Message ); errorMessage = String.Concat( errorMessage, " Line: " ); errorMessage = String.Concat( errorMessage, theException.Source ); MessageBox.Show( errorMessage, "Error" ); } }
メモ Visual Studio 2005 でコードを変更する必要があります。 既定では、Visual C# は、Windows フォーム プロジェクトを作成するときに、1 つのフォームをプロジェクトに追加します。 フォームは Form1 という名前です。 フォームを表す 2 つのファイルは、Form1.cs と Form1.designer.cs という名前です。 Form1.cs でコードを記述します。 Form1.designer.cs ファイルは、Windows フォーム デザイナーがツールボックスからコントロールをドラッグ アンド ドロップすることによって実行したすべてのアクションを実装するコードを記述する場所です。
Visual C# 2005 のWindows フォーム デザイナーの詳細については、次の Microsoft Developer Network (MSDN) Web サイトを参照してください。
Form1 のデザイン ビューに戻り、Button2 をダブルクリックします。
コード ウィンドウで、次のコードを置き換えます。
private void button2_Click(object sender, System.EventArgs e)
{
}
置換後:
private void button2_Click(object sender, System.EventArgs e)
{
Excel.Sheets objSheets;
Excel._Worksheet objSheet;
Excel.Range range;
try
{
try
{
//Get a reference to the first sheet of the workbook.
objSheets = objBook.Worksheets;
objSheet = (Excel._Worksheet)objSheets.get_Item(1);
}
catch( Exception theException )
{
String errorMessage;
errorMessage = "Can't find the Excel workbook. Try clicking Button1 " +
"to create an Excel workbook with data before running Button2.";
MessageBox.Show( errorMessage, "Missing Workbook?");
//You can't automate Excel if you can't find the data you created, so
//leave the subroutine.
return;
}
//Get a range of data.
range = objSheet.get_Range("A1", "E5");
//Retrieve the data from the range.
Object[,] saRet;
saRet = (System.Object[,])range.get_Value( Missing.Value );
//Determine the dimensions of the array.
long iRows;
long iCols;
iRows = saRet.GetUpperBound(0);
iCols = saRet.GetUpperBound(1);
//Build a string that contains the data of the array.
String valueString;
valueString = "Array Data\n";
for (long rowCounter = 1; rowCounter <= iRows; rowCounter++)
{
for (long colCounter = 1; colCounter <= iCols; colCounter++)
{
//Write the next value into the string.
valueString = String.Concat(valueString,
saRet[rowCounter, colCounter].ToString() + ", ");
}
//Write in a new line.
valueString = String.Concat(valueString, "\n");
}
//Report the value of the array.
MessageBox.Show(valueString, "Array Values");
}
catch( Exception theException )
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat( errorMessage, theException.Message );
errorMessage = String.Concat( errorMessage, " Line: " );
errorMessage = String.Concat( errorMessage, theException.Source );
MessageBox.Show( errorMessage, "Error" );
}
}
コード ウィンドウの上部までスクロールします。 using ディレクティブの一覧の末尾に次の行を追加します。
using System.Reflection; using Excel = Microsoft.Office.Interop.Excel;
Automation クライアントをテストする
- F5 キーを押してビルドし、サンプル プログラムを実行します。
- Button1 をクリックします。 プログラムは新しいブックで Microsoft Excel を起動し、最初のワークシートのセル A1:E5 に配列の数値データを設定します。
- Button2 をクリックします。 プログラムは、セル A1:E5 のデータを新しい配列に取得し、結果をメッセージ ボックスに表示します。
- FillWithStrings を選択し、Button1 をクリックしてセル A1:E5 に文字列データを入力します。
関連情報
詳細については、次の Microsoft Developer Network (MSDN) Web サイトを参照してください。