25. Automatisation avec les données Excel
Lorsque des données sont fournies à Excel, comme indiqué dans Liaisons de données Excel, vous pouvez utiliser les fonctions UpdateChart
et PresentationFromTemplate
pour contrôler de manière programmée à l’aide de ces données.
Avec UpdateChart
vous échangez la feuille de données d’un graphique spécifique contre vos données. Avec PresentationFromTemplate
, vous utilisez vos données pour créer une nouvelle présentation basée sur un modèle PowerPoint comportant des graphiques think-cell liés aux plages de données d’Excel.
Étant intégrée au modèle Office Automation, l’interface avec les deux fonctions est accessible avec tout langage permettant de programmer Office, tel que VBA (Visual Basic for Applications) ou C#.
Le point d'entrée dans think-cell est l'objet complément think-cell, accessible via la collection Application.COMAddIns
. Les appels à think-cell sont toujours à liaison tardive. Pour plus d'explications, reportez-vous à la base de connaissances de Microsoft :
http://support.microsoft.com/kb/245115
Ainsi, le type de l'objet complément think-cell est simplement Object
, et il n'existe aucune bibliothèque ou référence de types à ajouter. Il suffit d'acquérir l'objet pour être en mesure de l'appeler :
Dim tcaddin As Object
Set tcaddin = Application.COMAddIns("thinkcell.addin").Object
25.1 Tableau de mise à jour
25.1.1 Signature
tcaddin.UpdateChart( _
pres As PowerPoint.Presentation, _
strName As String, _
rgData As Excel.Range, _
bTransposed As Boolean _
)
25.1.2 Description
Exécutée depuis Excel, cette fonction met à jour le graphique strName
dans pres
avec les nombres contenus dans rgData
. La plage rgData
doit être conforme à la structure décrite dans Création d’un graphique à partir d’Excel.
Notez que l’objet de la présentation pres
peut également être utilisé pour faire référence à une série de diapositives dans une présentation. Pour plus d’informations, consultez :
http://msdn.microsoft.com/en-us/vba/powerpoint-vba/articles/slide-object-powerpoint
Le nom du graphique strName
ne tient pas compte de la casse. Il doit avoir été attribué au préalable dans PowerPoint à l’aide du contrôle de propriété Nom UpdateChart, tel que décrit dans Présentation de l’automatisation. Le nom du graphique doit être unique dans la présentation ou la série de diapositives définies par pres
.
Si le graphique est lié à une plage de données Excel lors de l'invocation de cette fonction, le lien est interrompu. après quoi le graphique n'est plus lié à aucune plage Excel.
25.1.3 Exemple
Pour utiliser cet exemple, dans la fenêtre Visual Basic for Applications d’Excel, sélectionnez Outils, puis Références et ajoutez la bibliothèque d’objets 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
L’exemple suivant montre comment utiliser UpdateChart
à partir de 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 PrésentationdepuisModèle
25.2.1 Signature
tcaddin.PresentationFromTemplate( _
wb As Excel.Workbook, _
strTemplate As String, _
ppapp As PowerPoint.Application _
) As PowerPoint.Presentation
25.2.2 Description
Exécutée depuis Excel, cette fonction applique toute liaison de données dans wb
au modèle dont le nom de fichier est strTemplate
. Il en résulte une nouvelle présentation dans l'instance PowerPoint ppapp
.
strTemplate
peut être un chemin complet ou un chemin relatif qui est alors indiqué par rapport à l'emplacement du fichier wb
du classeur Excel.
Tous les graphiques dans strTemplate
liés au classeur Excel wb
sont mis à jour (que l'option de mise à jour automatique soit activée ou non). Ensuite, leurs liaisons de données sont interrompues afin d'éviter toute autre modification de ces graphiques.
Les graphiques dans strTemplate
qui sont liés à des classeurs Excel autres que wb
ne sont pas modifiés et restent liés. Il est donc possible de mettre à jour des liaisons à partir de plusieurs classeurs Excel, en enregistrant le résultat de cette fonction en tant que nouveau modèle et en la rappelant avec le classeur suivant.
Si vous souhaitez contrôler les couleurs des segments du diagramme avec le lien Excel, vous pouvez régler le modèle de couleurs sur Utiliser le remplissage Excel en superposition (voir Jeu de couleurs). De même , pour contrôler le format des nombres avec la liaison Excel, activez l'option Utiliser le format Excel (voir Format des nombres). Veillez à définir la couleur d'arrière-plan et le format des nombres des cellules respectives dans Excel avant d'appeler PresentationFromTemplate
.
25.2.3 Exemple
Pour utiliser cet exemple, dans la fenêtre Visual Basic for Applications d’Excel, sélectionnez Outils, puis Références et ajoutez la bibliothèque d’objets 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
Création de graphiques
-
4.Présentation de la création de graphiques
-
5.Saisie de données
-
6.Libellés de texte
-
7.Histogrammes, graphique à lignes et graphiques à aires
-
8.Éléments décoratifs du graphique
-
9.Graphique en cascade
-
10.Graphique Mekko
-
11.Graphique à secteurs et en anneau
-
12.Graphiques en nuage de points et à bulles
-
13.Diagramme de Gantt (chronologie)