Come automatizzare Excel usando Visual C# per compilare o ottenere dati in un intervallo usando matrici

Riepilogo

Questo articolo illustra come automatizzare Microsoft Excel usando Microsoft Visual C# 2005 o Microsoft Visual C# .NET per compilare e recuperare valori in un intervallo di più celle usando matrici.

Ulteriori informazioni

Per riempire un intervallo di più celle senza popolamento di celle una alla volta, è possibile impostare la proprietà Value di un oggetto Range su una matrice bidimensionale. Analogamente, è possibile recuperare una matrice bidimensionale di valori per più celle contemporaneamente usando la proprietà Value. I passaggi seguenti illustrano questo processo sia per l'impostazione che per il recupero dei dati usando matrici bidimensionali.

Compilare il client di automazione per Microsoft Excel

  1. Avviare Microsoft Visual Studio 2005 o Microsoft Visual Studio .NET.

  2. Scegliere Nuovo dal menu File e quindi fare clic su Progetto. Selezionare Applicazione Windows dai tipi di progetto Visual C#. Form1 viene creato per impostazione predefinita.

  3. Aggiungere un riferimento alla libreria di oggetti di Microsoft Excel 11.0 in Visual Studio 2005 o nella libreria di oggetti di Microsoft Excel in Visual Studio .NET. A tal fine, attenersi alla seguente procedura:

    1. Scegliere Aggiungi riferimento dal menu Progetto.
    2. Nella scheda COM individuare Libreria oggetti di Microsoft Excel e quindi fare clic su Seleziona.

    In Visual Studio 2005 individuare Libreria oggetti di Microsoft Excel 11.0 nella scheda COM .

    Nota Microsoft Office 2003 include assembly di interoperabilità primari ( PIA). Microsoft Office XP non include le FUNZIONALITÀ personali, ma può essere scaricato.

  4. Fare clic su OK nella finestra di dialogo Aggiungi riferimenti per accettare le selezioni. Se viene richiesto di generare wrapper per le librerie selezionate, fare clic su Sì.

  5. Nel menu Visualizza selezionare Casella degli strumenti per visualizzare la casella degli strumenti. Aggiungere due pulsanti e una casella di controllo a Form1.

  6. Impostare le proprietà Name e Text per la casella di controllo su FillWithStrings.

  7. Fare doppio clic su Button1. Viene visualizzata la finestra del codice per il modulo.

  8. Nella finestra del codice sostituire il codice seguente:

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

    Con:

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

    Nota È necessario modificare il codice in Visual Studio 2005. Per impostazione predefinita, Visual C# aggiunge una maschera al progetto quando si crea un progetto Windows Forms. Il modulo è denominato Form1. I due file che rappresentano il modulo sono denominati Form1.cs e Form1.designer.cs. Il codice viene scritto in Form1.cs. Nel file Form1.designer.cs il Windows Forms Designer scrive il codice che implementa tutte le azioni eseguite trascinando ed eliminando i controlli dalla casella degli strumenti.

    Per altre informazioni su Progettazione Windows Forms in Visual C# 2005, visitare il seguente sito Web Microsoft Developer Network (MSDN):

    Creazione di un progetto (Visual C#)

  9. Tornare alla visualizzazione progettazione per Form1 e fare doppio clic su Button2.

  10. Nella finestra del codice sostituire il codice seguente:

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

Con:

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. Scorrere fino alla parte superiore della finestra del codice. Aggiungere la riga seguente alla fine dell'elenco delle direttive using:

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

Testare il client di automazione

  1. Premere F5 per compilare ed eseguire il programma di esempio.
  2. Fare clic su Button1. Il programma avvia Microsoft Excel con una nuova cartella di lavoro e popola le celle A1:E5 del primo foglio di lavoro con i dati numerici di una matrice.
  3. Fare clic su Button2. Il programma recupera i dati nelle celle A1:E5 in una nuova matrice e visualizza i risultati in una finestra di messaggio.
  4. Selezionare FillWithStrings e quindi fare clic su Button1 per riempire le celle A1:E5 con i dati stringa.

Riferimenti

Per altre informazioni, visitare il seguente sito Web Microsoft Developer Network (MSDN):

Sviluppo di Microsoft Office con Visual Studio