26. Excelデータを使用しての自動化

データがExcelで提供されている場合、関数 UpdateChart および PresentationFromTemplate を使用して、そのデータを使用してプログラムで制御できます。

UpdateChart を使用すると、特定の要素のデータシートをExcelデータと交換できます。PresentationFromTemplate を使用すると、「22. Excel データ リンク」で説明されているように、データを使用してExcelのデータ範囲にリンクされたthink-cell要素を含むPowerPointテンプレートに基づく新しいプレゼンテーションを作成できます。

両方の機能へのインターフェイスはOffice オートメーション モデルに統合されているため、Visual Basic for Applications (VBA) やC#など、Officeをプログラミングできる任意の言語からアクセスできます。詳細な手順については、F.1 はじめにを参照してください。

think-cellへのエントリポイントは、think-cellアドイン オブジェクトです。これには Application.COMAddIns コレクションからアクセスできます。think-cellへの呼び出しは、常に遅延結合です。詳細は、Microsoftのサナレッジベースを参照してください。

自動化での事前バインディングと遅延バインディングの使用

このように、think-cellアドインオブジェクトのタイプは単に Object であり、追加するタイプライブラリまたは参照はありません。オブジェクトを取得するだけで、呼び出す準備が整います。たとえば、ExcelのVBAでは次のようになります。

Dim tcXlAddIn As Object 
Set tcXlAddIn = Application.COMAddIns("thinkcell.addin").Object

C#では、think-cellアドインオブジェクトへの参照を dynamic として宣言することで遅延バインディングを実現できます。 これは、参照を var として宣言するときにコンパイラによって推論される型でもあるため、単純に次のように記述できます。

var tcXlAddIn = xlapp.COMAddIns.Item("thinkcell.addin").Object;

ここで xlapp は、think-cellがロードされている Excel.Application オブジェクトへの参照です。

26.1 グラフの更新

26.1.1 署名

VBA
tcXlAddIn.UpdateChart( _ 
    target As Object, _ 
    strName As String, _ 
    rgData As Excel.Range, _ 
    bTransposed As Boolean _ 
)
C#
void tcXlAddIn.UpdateChart(
    object target,
    string strName,
    Excel.Range rgData,
    bool bTransposed
);

26.1.2 説明

この関数は、target 内の strName という名前のすべての要素を、rgData に含まれるデータで更新します。データがグラフで正しく解釈されるためには、範囲 rgData が既定のデータシート レイアウトまたはその転置されたバージョンに準拠している必要があります。22.1 Excelからのグラフ作成 および 22.2 データレイアウトの調整 も参照してください。bTransposed をそれぞれ false または true に設定することで、既定バージョンまたは転置バージョンのどちらを使用するかが示されます。グラフ以外の要素、たとえば表の場合、bTransposed の値は無視されます。

target は、 Presentation または SlideRange、または単一の SlideMaster、または CustomLayout でなければなりません。

グラフ名 strName は大文字と小文字を区別して整合されます。この機能は以前、25. オートメーション機能のご紹介にあるUpdateChart Name プロパティコントロールを使用してPowerPointに割り当てられていました。

正しい要素がターゲットとなるようにするには、UpdateChart Name.として渡されたオブジェクト内で、strNamepresに設定されている唯一の要素だけであることを確認してください。

この関数を呼び出すときに要素が何らかのExcelデータの範囲にリンクされていると、リンクが切断されます。その後、要素はいかなるExcelの範囲にもリンクされません。

26.1.3 例

これらのサンプルを使用するには、25. オートメーション機能のご紹介 の説明に従ってプレゼンテーションを準備し、C:\Samples\UpdateChart\template.pptx として保存します。

VBA

このサンプルを使用するには、Excelワークブックのモジュールに追加します。

(詳細はF.1.1 アプリケーション用の Visual Basicを参照)Microsoft PowerPoint 16.0 Object Libraryへの参照が必要です。

ワークブックで UpdateChart_Sample を実行すると、最初のシートの範囲 A1:D5 に含まれるデータでプレゼンテーション テンプレートのグラフが更新されます。

Option Explicit 
 
Sub UpdateChart_Sample() 

    ' Get the range containing the new data 
    Dim rng As Excel.Range 
    Set rng = ActiveWorkbook.Sheets(1).Range("A1:D5") 

    ' Get the think-cell add-in object 
    Dim tcXlAddIn As Object 
    Set tcXlAddIn = 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:\\Samples\\UpdateChart\\template.pptx", _
    '  Untitled:=msoTrue) 

    ' PowerPoint window invisible 

    Set pres = ppapp.Presentations.Open( _
    Filename:="C:\\Samples\\UpdateChart\\template.pptx", _
    Untitled:=msoTrue, _
    WithWindow:=msoFalse)

    Call tcXlAddIn.UpdateChart(pres, "Chart1", rng, False) 

    ' Save the updated presentation 
    pres.SaveAs ("C:\\Samples\\UpdateChart\\template_updated.pptx") 
    pres.Close 

    ppapp.Quit 
End Sub

C#

このサンプルを使用するには、C# Console Appのプロジェクト テンプレートの Program.cs 内のコードをそれに置き換えます。

Microsoft PowerPoint 16.0 Object LibraryMicrosoft Excel 16.0 Object Library、およびMicrosoft Office 16.0 Object Library への参照が必要です(詳細はF.1.2 C#を参照)。

結果のアプリケーションを実行すると、プレゼンテーション テンプレートのグラフが更新され、値が 1、2、3の「系列 1」という名前の単一の系列が含まれるようになり、結果がtemplate_updated.pptxとして保存されます。

using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Office = Microsoft.Office.Core;

namespace ConsoleApplication_UpdateChart
{
    class Program
    {
        static void Main()
        {
            Excel.Application xlapp = new Excel.Application { 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:\\Samples\\UpdateChart\\template.pptx",
                    Office.MsoTriState.msoFalse,
                    Office.MsoTriState.msoTrue
            );

            var tcXlAddIn = xlapp.COMAddIns.Item("thinkcell.addin").Object;
            tcXlAddIn.UpdateChart(
                presentation,
                "Chart1",
                worksheet.get_Range("A1", "D3"),
                false
            );

            presentation.SaveAs("C:\\Samples\\UpdateChart\\template_updated.pptx");
            presentation.Close();
            ppapp.Quit();

            workbook.Close(false);
            xlapp.Quit();
        }
    }
}

26.2 テンプレートからのプレゼンテーション

26.2.1 署名

VBA
tcXlAddIn.PresentationFromTemplate( _ 
    wb As Excel.Workbook, _ 
    strTemplate As String, _ 
    ppapp As PowerPoint.Application _ 
) As PowerPoint.Presentation
C#
PowerPoint.Presentation tcXlAddIn.PresentationFromTemplate(
    Excel.Workbook wb,
    string strTemplate,
    PowerPoint.Application ppapp
);

26.2.2 説明

この関数は、Excelワークブック wb とファイル名が strTemplate のテンプレートとの間のデータリンクを使用して、リンク先の範囲のデータでリンクされた要素を更新することにより、そのテンプレートをインスタンス化します。その結果、PowerPointインスタンス ppapp 内に新しいプレゼンテーションが作成されます。

strTemplate は完全なパスでも相対パスでもかまいませんが、その後、Excelのブックファイル wb の場所に関連付けられます。

Excelワークブック wb にリンクされている strTemplate のすべての要素は、(自動更新に設定されているかどうかに関係なく) 更新されます。結果のプレゼンテーションでは、これらの要素がさらに変更されるのを防ぐために、それらのデータ リンクが壊れています。

wb 以外のExcelワークブックにリンクされている strTemplate の要素は変更されずにリンクされているため、この関数の結果を新しいテンプレートとして保存して次のブックでこの関数を再度呼び出すことで、複数のExcelワークブックからリンクを更新できます。

Excelリンクを使用してグラフセグメントの色または表のセルのフォーマットを制御する場合は、配色を Use Datasheet Fill on Top (3.4.2 配色を参照) または Use Datasheet... オプション (17.3 表の書式設定を参照) にそれぞれ設定できます。同様に、Excelリンクで表示形式をコントロールするには、Use Excel Formatに設定します (6.5.3 数値形式を参照)。

PresentationFromTemplate を呼び出す前に、Excelの各セルの背景色と数値形式を設定してください。

26.2.3 例

これらのサンプルを使用するには、まず 22.1 Excelからのグラフ作成 で説明されているように、Excelワークブックの最初のシートの範囲 G1:K4 にリンクされた積み上げグラフを含むプレゼンテーションを作成します。結果のプレゼンテーションを C:\Samples\PresentationFromTemplate\template.pptx として保存し、ワークブックを data.xlsx として同じディレクトリに保存します。

VBA

このサンプルを使用するには、上記で準備したExcelワークブック data.xlsx のモジュールに追加します。

(詳細はF.1.1 アプリケーション用の Visual Basicを参照)Microsoft PowerPoint 16.0 Object Libraryへの参照が必要です。

PresentationFromTemplate_Sample を実行すると、template.pptx に含まれるチャートの最初の系列の最初の値にリンクされているセル Sheet1!H3 の値が i=1 から 10 に変更され、その値を含むように更新されたテンプレート内のグラフで新しいプレゼンテーションが作成されます。 これはワークブックにリンクされなくなり、テンプレートと同じディレクトリに output_i.pptx として保存します。

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(1).Cells(3, 8)

    ' Get the think-cell add-in object
    Dim tcXlAddIn As Object
    Set tcXlAddIn = 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
        ' GOOD:
        rng.Value = i

        ' Generate a new presentation based on the
        ' linked template.
        Dim pres As PowerPoint.Presentation
        Set pres = tcXlAddIn.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:\Samples\PresentationFromTemplate\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

C#

このサンプルを使用するには、C# Console Appプロジェクトテンプレートの Program.cs 内のコードをそれに置き換えます。

Microsoft PowerPoint 16.0 Object LibraryMicrosoft Excel 16.0 Object Library、およびMicrosoft Office 16.0 Object Library への参照が必要です(詳細はF.1.2 C#を参照)。

結果のアプリケーションを実行すると、目に見えて Excel が開き、ワークブック data.xlsx が読み込まれ、template.pptx に含まれるグラフの最初の系列の最初の値にリンクされているセル H3 の値が i=1 から 10 に変更され、その値を含むように更新されたテンプレート内のグラフで新しいプレゼンテーションが作成されます。 これはワークブックにリンクされなくなり、テンプレートと同じディレクトリに output_i.pptx として保存します。

using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication_PresentationFromTemplate
{
    class Program
    {
        static void Main()
        {
            var xlapp = new Excel.Application { Visible = true };
            var tcXlAddIn = xlapp.COMAddIns.Item("thinkcell.addin").Object;
            var workbook = xlapp.Workbooks.Open("C:\\Samples\\PresentationFromTemplate\\data.xlsx");
            var ppapp = new PowerPoint.Application();
            for (var i = 1; i <= 10; ++i)
            {
                workbook.Sheets[1].Cells[3, 8] = i;

                PowerPoint.Presentation presentation = tcXlAddIn.PresentationFromTemplate(
                    workbook,
                    "C:\\Samples\\PresentationFromTemplate\\template.pptx",
                    ppapp
                );

                presentation.SaveAs("C:\\Samples\\PresentationFromTemplate\\output" + i + ".pptx");
                presentation.Close();
            }
            ppapp.Quit();
            workbook.Close(false);
            xlapp.Quit();
        }
    }
}

共有する