25. Automazione con dati Excel
Quando i dati vengono forniti in Excel come descritto in Collegamenti dati Excel, è possibile utilizzare le funzioni UpdateChart
e PresentationFromTemplate
per controllare in modo programmatico utilizzando tali dati.
Con UpdateChart
si scambia il foglio dati di un grafico specifico con i propri dati. Con PresentationFromTemplate
si utilizzano i propri dati per creare una nuova presentazione basata su un modello di PowerPoint con think-cell chart collegati a intervalli di dati in Excel.
L’interfaccia a entrambe le funzioni è integrata nel modello di automazione di Office e risulta pertanto accessibile con ogni linguaggio con cui è possibile programmare Office, ad esempio Visual Basic for Applications o C#.
Il punto di ingresso in think-cell è l’oggetto componente aggiuntivo di think-cell. È accessibile tramite la collezione Application.COMAddIns
. Le chiamate a think-cell sono sempre ad associazione tardiva. Una spiegazione è fornita nella Knowledge base di Microsoft:
http://support.microsoft.com/kb/245115
Il tipo dell’oggetto componente aggiuntivo di think-cell è dunque semplicemente Object
e non è necessario aggiungere alcuna libreria dei tipi o alcun riferimento. È sufficiente acquisire l’oggetto per essere pronti a effettuare delle chiamate:
Dim tcaddin As Object
Set tcaddin = Application.COMAddIns("thinkcell.addin").Object
25.1 Aggiornamento grafico
25.1.1 Firma
tcaddin.UpdateChart( _
pres As PowerPoint.Presentation, _
strName As String, _
rgData As Excel.Range, _
bTransposed As Boolean _
)
25.1.2 Descrizione
Richiamata da Excel, questa funzione aggiorna il grafico strName
in pres
con i numeri contenuti in rgData
. L’intervallo rgData
deve essere conforme al layout descritto in Creazione di un grafico da Excel.
Nota: l’oggetto presentazione pres
può essere utilizzato anche come riferimento a un intervallo di diapositive in una presentazione. Per maggiori informazioni, fare riferimento a:
http://msdn.microsoft.com/en-us/vba/powerpoint-vba/articles/slide-object-powerpoint
Il nome del grafico strName
non fa distinzione tra maiuscole e minuscole. Deve essere stato precedentemente assegnato in PowerPoint utilizzando il controllo della proprietà Nome UpdateChart descritto in Introduzione all’automazione. Il nome del grafico deve essere univoco all’interno della presentazione o dell’intervallo di diapositive definito da pres
.
Se il grafico è collegato a un intervallo di dati di Excel, quando si richiama questa funzione, il collegamento viene interrotto. In seguito il grafico non sarà più collegato ad alcun intervallo Excel.
25.1.3 Esempio
Per usare questo modello, nella finestra Visual Basic for Applications di Excel selezionare Strumenti, quindi Riferimenti e aggiungere la libreria di oggetti di Microsoft PowerPoint.
' When Option Explicit appears in a file, you must
' explicitly declare all variables using the Dim
' or ReDim statements. If you attempt to use an
' undeclared variable name, an error occurs at
' compile time.
' Use Option Explicit to avoid incorrectly typing
' the name of an existing variable or to avoid
' confusion in code where the scope of the
' variable is not clear. If you do not use the
' Option Explicit statement, all undeclared
' variables are of Object type.
' http://msdn.microsoft.com/en-us/
' library/y9341s4f%28v=vs.80%29.aspx
Option Explicit
Sub UpdateChart_Sample()
' Get the range containing the new data
Dim rng As Excel.Range
Set rng = ActiveWorkbook.Sheets("Sheet1").Range("A1:D5")
' Get the think-cell add-in object
Dim tcaddin As Object
Set tcaddin = Application.COMAddIns("thinkcell.addin").Object
' Get a PowerPoint instance. Hold on to this
' object as long as you want to access the
' generated presentations. There can only be a
' single PowerPoint instance. If there is no
' PowerPoint running, one will be started.
' Otherwise the existing one is used.
Dim ppapp As Object
Set ppapp = New PowerPoint.Application
Dim pres As PowerPoint.Presentation
' PowerPoint window visible
' Set pres = ppapp.Presentations.Open( _
' Filename:="c:\\template.pptx", _
' Untitled:=msoTrue)
' PowerPoint window invisible
Set pres = ppapp.Presentations.Open( _
Filename:="c:\\template.pptx", _
Untitled:=msoTrue, _
WithWindow:=msoFalse)
' The name "Chart1" must have been
' previously assigned to the chart using
' the control in the floating toolbar.
' The final argument indicates whether
' the data range is transposed or not.
Call tcaddin.UpdateChart(pres, "Chart1", rng, False)
' Save the updated presentation
pres.SaveAs ("c:\\template_updated.pptx")
pres.Close
ppapp.Quit
End Sub
Il prossimo esempio spiega come usare UpdateChart
da C#.
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Office = Microsoft.Office.Core;
// Open the Solution Explorer > right-click the project file > "Add Reference..." button and add he following references:
// .NET tab > Microsoft.Office.Interop.Excel 12.0.0.0
// .NET tab > Microsoft.Office.Interop.PowerPoint 12.0.0.0
// COM tab > Microsoft Office 14.0 Object Library
namespace ConsoleApplication_UpdateChart
{
class Program
{
static void Main()
{
Excel.Application xlapp = new Excel.Application();
xlapp.Visible = true;
Excel.Workbook workbook = xlapp.Workbooks.Add(1);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1];
worksheet.Cells[3, 1] = "Series 1";
worksheet.Cells[3, 2] = 1;
worksheet.Cells[3, 3] = 2;
worksheet.Cells[3, 4] = 3;
PowerPoint.Application ppapp = new PowerPoint.Application();
PowerPoint.Presentation presentation =
ppapp.Presentations.Open("C://template.pptx", Office.MsoTriState.msoFalse, Office.MsoTriState.msoTrue);
object[] aobjArg = new object[] { (object)presentation, "Chart1", worksheet.get_Range("A1", "D3"), false };
Office.COMAddIn comaddin = xlapp.COMAddIns.Item("thinkcell.addin");
object objAddIn = comaddin.Object;
objAddIn.GetType().InvokeMember("UpdateChart", System.Reflection.BindingFlags.InvokeMethod, null, objAddIn, aobjArg);
presentation.SaveAs("C://template_updated.pptx");
presentation.Close();
ppapp.Quit();
workbook.Close(false);
xlapp.Quit();
}
}
}
25.2 Presentazione da modello
25.2.1 Firma
tcaddin.PresentationFromTemplate( _
wb As Excel.Workbook, _
strTemplate As String, _
ppapp As PowerPoint.Application _
) As PowerPoint.Presentation
25.2.2 Descrizione
Richiamata da Excel, questa funzione applica tutti i collegamenti dati presenti in wb
al modello con nome file strTemplate
. Il risultato è una nuova presentazione entro l’istanza PowerPoint ppapp
.
strTemplate
può essere un percorso completo o un percorso relativo, che viene poi considerato un percorso relativo rispetto alla posizione del file della cartella di lavoro Excel wb
.
Tutti i grafici in strTemplate
collegati alla cartella di lavoro Excel wb
vengono aggiornati (indipendentemente dal fatto che per essi sia previsto o meno un aggiornamento automatico). I rispettivi collegamenti dati vengono quindi interrotti per impedire che ai grafici vengano apportate ulteriori modifiche.
I grafici in strTemplate
collegati a cartelle di lavoro Excel diverse da wb
restano invariati e risultano ancora collegati. In questo modo è possibile aggiornare i collegamenti da più cartelle di lavoro Excel salvando il risultato di questa funzione come nuovo modello e chiamando nuovamente questa funzione con la cartella di lavoro successiva.
Per controllare i colori dei segmenti del grafico con il collegamento di Excel, è possibile impostare la combinazione colori su Usa riempimento Excel (vedere Combinazione colori). Analogamente, per controllare il formato di numero tramite il collegamento Excel, impostarlo su Formato Excel (vedere Formato di numero). Accertarsi di avere impostato il colore dello sfondo e il formato numero delle rispettive celle in Excel prima di richiamare PresentationFromTemplate
.
25.2.3 Esempio
Per usare questo modello, nella finestra Visual Basic for Applications di Excel selezionare Strumenti, quindi Riferimenti e aggiungere la libreria di oggetti di Microsoft PowerPoint.
' When Option Explicit appears in a file, you must
' explicitly declare all variables using the Dim
' or ReDim statements. If you attempt to use an
' undeclared variable name, an error occurs at
' compile time.
' Use Option Explicit to avoid incorrectly typing
' the name of an existing variable or to avoid
' confusion in code where the scope of the
' variable is not clear. If you do not use the
' Option Explicit statement, all undeclared
' variables are of Object type.
' http://msdn.microsoft.com/en-us/
' library/y9341s4f%28v=vs.80%29.aspx
Option Explicit
Sub PresentationFromTemplate_Sample()
' Get the range to modify. It is more efficient
' to do this once rather than within the loop.
Dim rng As Excel.Range
Set rng = ActiveWorkbook.Sheets("Sheet1").Cells(3, 2)
' Get the think-cell add-in object
Dim tcaddin As Object
Set tcaddin = Application.COMAddIns("thinkcell.addin").Object
' Get a PowerPoint instance. Hold on to this
' object as long as you want to access the
' generated presentations. There can only be a
' single PowerPoint instance. If there is no
' PowerPoint running, one will be started.
' Otherwise the existing one is used.
Dim ppapp As Object
Set ppapp = New PowerPoint.Application
Dim i As Integer
For i = 1 To 10
' Modify the range value.
' Note: Avoid selecting the cell prior to
' changing it. It is very slow and has
' undesirable side-effects.
' BAD:
' rng.Select
' ActiveWindow.Selection.Value = 0
rng.Value = i
' Generate a new presentation based on the
' linked template.
Dim pres As PowerPoint.Presentation
Set pres = tcaddin.PresentationFromTemplate( _
Excel.ActiveWorkbook, "template.pptx", ppapp)
' If you want to modify the new presentation
' before saving it this is the place to do it.
' Save the new presentation
pres.SaveAs "c:\\output" & i & ".pptx"
' Explicitly close the presentation when we
' are done with it to free its memory.
' Letting the object go out of scope is not
' sufficient.
pres.Close
Next
End Sub
Grafici
-
4.Introduzione alla creazione di grafici
-
5.Inserimento dati
-
6.Etichette di testo
-
7.Istogramma, grafico a linee e ad area
-
8.Elementi decorativi dei grafici
-
9.Grafico a cascata
-
10.Grafico Mekko
-
11.Grafico a torta e a ciambella
-
12.Grafico a dispersione e grafico a bolle
-
13.Diagramma di Gantt (linea temporale)