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.
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
Avviare Microsoft Visual Studio 2005 o Microsoft Visual
Studio .NET.
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.
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:
Scegliere Aggiungi riferimento dal menu Progetto.
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
Scegliere OK nella finestra di dialogo Aggiungi riferimento per accettare le selezioni. Se viene richiesto di generare
wrapper per le librerie selezionate, scegliere Sì.
Scegliere Casella degli strumenti dal menu Visualizza per visualizzare la casella degli strumenti. Aggiungere due
pulsanti e una casella di controllo a Form1.
Impostare le proprietà Name e Text relative alla casella di controllo su FillWithStrings.
Fare doppio clic su Button1. Viene visualizzata la finestra del codice per il
form.
Nella finestra del codice sostituire il codice riportato di
seguito
//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):
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" );
}
}
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
Premere F5 per compilare ed eseguire il programma di
esempio.
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.
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.
Selezionare FillWithStrings, quindi fare clic su Button1 per inserire i dati stringa nelle celle A1:E5.
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 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.
Lasciare un commento su queste informazioni
Queste informazioni hanno risolto il problema?
Sì
No
Non so
Queste informazioni erano pertinenti?
Sì
No
In che modo possiamo migliorarle?
Per salvaguardare la privacy, non includere informazioni personali nei commenti.
Grazie. I commenti e suggerimenti forniti verranno utilizzati per migliorare la qualità dei contenuti di supporto tecnico. Per ulteriori opzioni di assistenza, visitare la home page del Supporto Tecnico Microsoft.