Dizileri kullanarak bir aralıktaki verileri doldurmak veya almak için Visual C# kullanarak Excel'i otomatikleştirme

Özet

Bu makalede, dizileri kullanarak çok hücreli bir aralıktaki değerleri doldurmak ve almak için Microsoft Visual C# 2005 veya Microsoft Visual C# .NET kullanarak Microsoft Excel'i otomatikleştirme gösterilmektedir.

Daha Fazla Bilgi

Çok hücreli bir aralığı hücreleri birer birer doldurmadan doldurmak için, Range nesnesinin Value özelliğini iki boyutlu bir dizi olarak ayarlayabilirsiniz. Benzer şekilde, Value özelliğini kullanarak aynı anda birden çok hücre için iki boyutlu bir değer dizisi alabilirsiniz. Aşağıdaki adımlar, iki boyutlu dizileri kullanarak verileri ayarlamaya ve almaya yönelik bu işlemi gösterir.

Microsoft Excel için Otomasyon İstemcisi'ni oluşturma

  1. Microsoft Visual Studio 2005 veya Microsoft Visual Studio .NET'i başlatın.

  2. Dosya menüsünde Yeni'ye ve ardından Proje'ye tıklayın. Visual C# Proje türlerinden Windows Uygulaması'nı seçin. Form1 varsayılan olarak oluşturulur.

  3. Visual Studio 2005'te Microsoft Excel 11.0 Nesne Kitaplığı'na veya Visual Studio .NET'te Microsoft Excel Nesne Kitaplığı'na başvuru ekleyin. Bunu yapmak için şu adımları uygulayın:

    1. Proje menüsünde Başvuru Ekle'ye tıklayın.
    2. COM sekmesinde Microsoft Excel Nesne Kitaplığı'nı bulun ve Seç'e tıklayın.

    Visual Studio 2005'te, COM sekmesinde Microsoft Excel 11.0 Nesne Kitaplığı'nı bulun.

    Not Microsoft Office 2003, Birincil Birlikte Çalışma Derlemelerini (PIA) içerir. Microsoft Office XP PIA içermez, ancak indirilebilir.

  4. Seçimlerinizi kabul etmek için Başvuru Ekle iletişim kutusunda Tamam'a tıklayın. Seçtiğiniz kitaplıklar için sarmalayıcılar oluşturmanız istenirse Evet'e tıklayın.

  5. Görünüm menüsünde Araç Kutusu'nu seçerek Araç Kutusu'nu görüntüleyin. Form1'e iki düğme ve onay kutusu ekleyin.

  6. Onay kutusunun Ad ve Metin özelliklerini FillWithStrings olarak ayarlayın.

  7. Düğme1'e çift tıklayın. Formun kod penceresi görüntülenir.

  8. Kod penceresinde aşağıdaki kodu değiştirin:

    private void button1_Click(object sender, System.EventArgs e)
    {
    }
    

    Ile:

       //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" );
          }
       }
    

    Not Visual Studio 2005'te kodu değiştirmeniz gerekir. Varsayılan olarak, Windows Forms proje oluşturduğunuzda Visual C# projeye bir form ekler. Form, Form1 olarak adlandırılır. Formu temsil eden iki dosya Form1.cs ve Form1.designer.cs olarak adlandırılır. Kodu Form1.cs'de yazarsınız. Form1.designer.cs dosyası, Windows Forms Tasarımcısı'nın Denetimleri Araç Kutusu'ndan sürükleyip bırakarak gerçekleştirdiğiniz tüm eylemleri uygulayan kodu yazdığı yerdir.

    Visual C# 2005'teki Windows Forms Tasarımcısı hakkında daha fazla bilgi için aşağıdaki Microsoft Developer Network (MSDN) Web sitesini ziyaret edin:

    Proje Oluşturma (Visual C#)

  9. Form1'in tasarım görünümüne dönün ve Düğme2'ye çift tıklayın.

  10. Kod penceresinde aşağıdaki kodu değiştirin:

private void button2_Click(object sender, System.EventArgs e)
{
}

Ile:

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" );
      }
   }
  1. Kod penceresinin en üstüne kaydırın. Kullanma yönergeleri listesinin sonuna aşağıdaki satırı ekleyin:

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

Otomasyon İstemcisini Test Edin

  1. Örnek programı derlemek ve çalıştırmak için F5 tuşuna basın.
  2. Düğme1'e tıklayın. Program, Microsoft Excel'i yeni bir çalışma kitabıyla başlatır ve ilk çalışma sayfasının A1:E5 hücrelerini bir dizideki sayısal verilerle doldurur.
  3. Düğme2'ye tıklayın. Program, A1:E5 hücrelerindeki verileri yeni bir diziye alır ve sonuçları bir ileti kutusunda görüntüler.
  4. FillWithStrings'i seçin ve ardından A1:E5 hücrelerini dize verileriyle doldurmak için Düğme1'e tıklayın.

Başvurular

Daha fazla bilgi için aşağıdaki Microsoft Developer Network (MSDN) Web sitesini ziyaret edin:

Visual Studio ile Microsoft Office Geliştirme