Identificativo articolo: 302096 - Ultima modifica: lunedì 19 marzo 2007 - Revisione: 8.6

Automazione di Excel tramite Visual C# per inserire o ottenere dati in un intervallo mediante matrici

Questo articolo è stato precedentemente pubblicato con il codice di riferimento I302096
Espandi tutto | Chiudi tutto

Sommario

In questo articolo viene spiegato come automatizzare Microsoft Excel tramite Microsoft Visual C# 2005 o Microsoft Visual C# .NET per inserire e recuperare valori in un intervallo di celle mediante matrici.

Informazioni

Per compilare un intervallo di più celle senza popolare le celle una alla volta, è possibile impostare la proprietà Value di un oggetto Range su una matrice bidimensionale. Allo stesso modo, è possibile recuperare una matrice bidimensionale di valori per più celle in una sola volta utilizzando la proprietà Value. La seguente procedura mostra questo processo sia per l'impostazione che per il recupero di dati mediante 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, quindi Progetto. Selezionare Applicazione per Windows dai tipi di progetto di Visual C#. Per impostazione predefinita, viene creato il progetto Form1.
  3. Aggiungere un riferimento a Libreria oggetti di Microsoft Excel 11.0 in Visual Studio 2005 o a Libreria oggetti di Microsoft Excel in Visual Studio .NET. A questo scopo, attenersi alla procedura seguente:
    1. Scegliere Aggiungi riferimento dal menu Progetto.
    2. Nella scheda COM individuare Libreria oggetti di Microsoft Excel, quindi scegliere Seleziona.

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

      Nota Microsoft Office 2003 include gli assembly di interoperabilità primari (PIA, Primary Interop Assembly). Non sono invece inclusi in Microsoft Office XP, ma possono essere scaricati. Per ulteriori informazioni sugli assembly di interoperabilità primari di Office XP, fare clic sul numero dell'articolo della Microsoft Knowledge Base riportato di seguito:
      328912  (http://support.microsoft.com/kb/328912/ ) Assembly di interoperabilità primari (PIA) di Microsoft Office XP disponibili per il download
    3. Scegliere OK nella finestra di dialogo Aggiungi riferimento per accettare le selezioni. Se viene richiesto di generare wrapper per le librerie selezionate, scegliere .
  4. Scegliere Casella degli strumenti dal menu Visualizza per visualizzare la casella degli strumenti. Aggiungere due pulsanti e una casella di controllo a Form1.
  5. Impostare le proprietà Name e Text relative alla casella di controllo su FillWithStrings.
  6. Fare doppio clic su Button1. Viene visualizzata la finestra del codice per il form.
  7. Nella finestra del codice sostituire il codice riportato di seguito
    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, in Visual C# viene aggiunto un form al progetto quando si crea un progetto Windows Form. Il nome del form è Form1. I due file che rappresentano il form sono denominati Form1.cs e Form1.designer.cs. Il codice viene scritto in Form1.cs. Nel file Form1.designer.cs Progettazione Windows Form scrive il codice che implementa tutte le azioni eseguite trascinando e rilasciando i controlli dalla Casella degli strumenti.

    Per ulteriori informazioni su Progettazione Windows Form in Visual C# 2005, visitare il seguente sito Web Microsoft Developer Network (MSDN):
    http://msdn2.microsoft.com/it-it/library/ms173077(VS.80).aspx (http://msdn2.microsoft.com/it-it/library/ms173077(VS.80).aspx)
  8. Ritornare alla visualizzazione Progettazione di Form1 e fare doppio clic su Button2.
  9. Nella finestra del codice sostituire il codice riportato di seguito
    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" );
             }
          }
  10. Scorrere verso l'alto la pagina del codice. Aggiungere la riga seguente alla fine dell'elenco di direttive using:
    using System.Reflection;
    using Excel = Microsoft.Office.Interop.Excel;

Verifica del client di automazione

  1. Premere F5 per compilare ed eseguire il programma di esempio.
  2. Fare clic su Button1. Viene avviato Microsoft Excel con una nuova cartella di lavoro e le celle A1:E5 del primo foglio di lavoro vengono popolate con dati numerici da una matrice.
  3. Fare clic su Button2. I dati nelle celle A1:E5 vengono recuperati in una nuova matrice e i risultati sono visualizzati in una finestra di messaggio.
  4. Selezionare FillWithStrings, quindi fare clic su Button1 per inserire i dati stringa nelle celle A1:E5.

Riferimenti

Per ulteriori informazioni, visitare il seguente sito Web MSDN (informazioni in lingua inglese):
Microsoft Office Development with Visual Studio
http://msdn2.microsoft.com/en-us/library/aa188489(office.10).aspx (http://msdn2.microsoft.com/en-us/library/aa188489(office.10).aspx)
Per ulteriori informazioni sull'utilizzo di matrici per impostare e recuperare dati di Excel con versioni precedenti di Visual Studio, fare clic sui numeri degli articoli della Microsoft Knowledge Base riportati di seguito:
186120  (http://support.microsoft.com/kb/186120/ ) Utilizzo di MFC per automatizzare Excel e compilare un intervallo con una matrice
186122  (http://support.microsoft.com/kb/186122/ ) Utilizzo di MFC per automatizzare Excel e ottenere una matrice da un intervallo
247412  (http://support.microsoft.com/kb/247412/ ) Metodi per il trasferimento di dati da Visual Basic a Excel

Le informazioni in questo articolo si applicano a:
  • Microsoft Visual C# 2005 Express Edition
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Office Excel 2003
  • Microsoft Excel 2002 Standard Edition
Chiavi: 
kbautomation kbhowto KB302096
LE INFORMAZIONI CONTENUTE NELLA MICROSOFT KNOWLEDGE BASE SONO FORNITE SENZA GARANZIA DI ALCUN TIPO, IMPLICITA OD ESPLICITA, COMPRESA QUELLA RIGUARDO ALLA COMMERCIALIZZAZIONE E/O COMPATIBILITA' IN IMPIEGHI PARTICOLARI. L'UTENTE SI ASSUME L'INTERA RESPONSABILITA' PER L'UTILIZZO DI QUESTE INFORMAZIONI. IN NESSUN CASO MICROSOFT CORPORATION E I SUOI FORNITORI SI RENDONO RESPONSABILI PER DANNI DIRETTI, INDIRETTI O ACCIDENTALI CHE POSSANO PROVOCARE PERDITA DI DENARO O DI DATI, ANCHE SE MICROSOFT O I SUOI FORNITORI FOSSERO STATI AVVISATI. IL DOCUMENTO PUO' ESSERE COPIATO E DISTRIBUITO ALLE SEGUENTI CONDIZIONI: 1) IL TESTO DEVE ESSERE COPIATO INTEGRALMENTE E TUTTE LE PAGINE DEVONO ESSERE INCLUSE. 2) I PROGRAMMI SE PRESENTI, DEVONO ESSERE COPIATI SENZA MODIFICHE, 3) IL DOCUMENTO DEVE ESSERE DISTRIBUITO INTERAMENTE IN OGNI SUA PARTE. 4) IL DOCUMENTO NON PUO' ESSERE DISTRIBUITO A SCOPO DI LUCRO.
 

Traduzione articoli

 

Related Support Centers