フッターコンテンツにスキップ
PPTツール
C#を使用してPowerPointプレゼンテーションを作成する方法

How to Programmatically Create and Automate PowerPoint Presentations in C#

毎週同じ PowerPoint プレゼンテーションを手動で作成するのは、退屈でエラーが発生しやすい作業であり、開発者は誰もやりたくない作業です。 毎週の売上レポート、毎月の財務概要、またはパーソナライズされたクライアント提案の作成など、プロセスは自動化に最適です。 長い間、.NETの世界では、プログラムでOfficeアプリケーションを制御できるMicrosoft Office Interopが定番のソリューションでした。 ただし、このアプローチには重大な欠点があります。サーバーにライセンス版の Microsoft Office をインストールする必要があり、サーバー環境では非常に不安定であることで有名で、Linux、macOS、または Docker コンテナーでの最新のクロスプラットフォーム展開は完全に不可能です。

幸いなことに、もっと良い方法があります。 このチュートリアルでは、IronPPT for .NETを使用してC#でプログラム的にPowerPointプレゼンテーションを作成する方法を示します。IronPPTは、モダンな開発のために設計された強力で軽量なライブラリです。 シンプルなスライド デッキの作成から、表やグラフを含むテンプレートからの複雑なデータ駆動型プレゼンテーションの生成まで、すべてを自動化する方法を説明します。 IronPPT を使用すると、Microsoft Office に依存せずに、どこでも実行できる高速でスケーラブルかつ信頼性の高いプレゼンテーション自動化ワークフローを構築できます。

IronPPT - C# プレゼンテーションライブラリ IronPPT for .NETライブラリは、開発者がC#でPowerPointファイルをプログラム的に生成および管理できるようにします.

PowerPoint生成をC#で始めるにはどうすればいいですか?

C# で PowerPoint 自動化を始めるのは簡単です。 IronPPT for .NETはNuGetパッケージとして配布されており、数秒でVisual Studioプロジェクトに直接インストールできます。

ステップ1: IronPPTライブラリをインストールする

Visual Studio でパッケージマネージャコンソールを開きます ( Tools > NuGet Package Manager > Package Manager Console ) そこで以下のコマンドを入力します:

Install-Package IronPPT

あるいは、NuGet パッケージ マネージャー GUI で"IronPPT"を検索し、そこからインストールすることもできます。

NuGet パッケージマネージャ画面を介して IronPPT をインストール Visual Studio の NuGet パッケージ マネージャー。IronPPT ライブラリのインストールが表示されています。

ステップ2: 最初のプレゼンテーションを作成して保存する

ライブラリをインストールすると、わずか数行の C# コードで最初の PowerPoint プレゼンテーションを作成できます。 すべてのプレゼンテーションの核心クラスは PresentationDocument です。

次のコードスニペットは新しいプレゼンテーションを初期化し、タイトル付きのスライドを一枚追加しそれを .pptx ファイルとして保存します。

using IronPPT;

// Before using IronPPT, a license key is required.
// Get a free 30-day trial key at: https://ironsoftware.com/csharp/ppt/licensing/#trial-license
License.LicenseKey = "YOUR-LICENSE-KEY";

// Create a new PowerPoint presentation document
var presentation = new PresentationDocument();

// Create a new slide object
var slide = new Slide();

// Add text to the slide, which will be placed in a default textbox
slide.AddText("Hello, World! Welcome to Programmatic PowerPoint Creation.");

// Add the slide to the presentation
presentation.AddSlide(slide);

// Save the presentation to a.pptx file
presentation.Save("MyFirstPresentation.pptx");
using IronPPT;

// Before using IronPPT, a license key is required.
// Get a free 30-day trial key at: https://ironsoftware.com/csharp/ppt/licensing/#trial-license
License.LicenseKey = "YOUR-LICENSE-KEY";

// Create a new PowerPoint presentation document
var presentation = new PresentationDocument();

// Create a new slide object
var slide = new Slide();

// Add text to the slide, which will be placed in a default textbox
slide.AddText("Hello, World! Welcome to Programmatic PowerPoint Creation.");

// Add the slide to the presentation
presentation.AddSlide(slide);

// Save the presentation to a.pptx file
presentation.Save("MyFirstPresentation.pptx");
Imports IronPPT

' Before using IronPPT, a license key is required.
' Get a free 30-day trial key at: https://ironsoftware.com/csharp/ppt/licensing/#trial-license
License.LicenseKey = "YOUR-LICENSE-KEY"

' Create a new PowerPoint presentation document
Dim presentation = New PresentationDocument()

' Create a new slide object
Dim slide As New Slide()

' Add text to the slide, which will be placed in a default textbox
slide.AddText("Hello, World! Welcome to Programmatic PowerPoint Creation.")

' Add the slide to the presentation
presentation.AddSlide(slide)

' Save the presentation to a.pptx file
presentation.Save("MyFirstPresentation.pptx")
$vbLabelText   $csharpLabel

このコードを実行すると、プロジェクトの出力ディレクトリに MyFirstPresentation.pptx という名前の新しいファイルが見つかります。 これを開くと、追加したテキストが入った 1 つのスライドが表示されます。 この簡単な例は、プレゼンテーション オブジェクトを作成し、コンテンツを追加し、ファイルを保存する基本的なワークフローを示しています。

IronPPT を使用して作成された空のプレゼンテーション C# と IronPPT を使用してプログラム的に作成された空白の PowerPoint プレゼンテーション。

プログラムでスライドを追加および操作するにはどうすればよいですか?

プレゼンテーションはスライドの集まりです。 IronPPT は、これらのスライドを管理するためのシンプルで直感的な API を提供し、アプリケーションの必要に応じてスライドを追加、読み込み、再利用できるようにします。

既存のプレゼンテーションの読み込みとスライドの追加

多くの場合、プレゼンテーションを最初から作成するのではなく、既存のプレゼンテーションを変更する必要があります。 ディスクから .pptx ファイルを読み込むには、そのパスを PresentationDocument コンストラクタに渡します。 読み込んだら、新しいスライドを簡単に追加できます。

次の例では、先ほど作成したプレゼンテーションを読み込み、新しい空白のスライドを追加します。

using IronPPT;

// Load an existing PowerPoint presentation
var presentation = new PresentationDocument("MyFirstPresentation.pptx");

// Add a new blank slide to the end of the presentation
presentation.AddSlide();

// Save the modified presentation
presentation.Save("PresentationWithTwoSlides.pptx");
using IronPPT;

// Load an existing PowerPoint presentation
var presentation = new PresentationDocument("MyFirstPresentation.pptx");

// Add a new blank slide to the end of the presentation
presentation.AddSlide();

// Save the modified presentation
presentation.Save("PresentationWithTwoSlides.pptx");
Imports IronPPT

' Load an existing PowerPoint presentation
Private presentation = New PresentationDocument("MyFirstPresentation.pptx")

' Add a new blank slide to the end of the presentation
presentation.AddSlide()

' Save the modified presentation
presentation.Save("PresentationWithTwoSlides.pptx")
$vbLabelText   $csharpLabel

この機能は、ログ記録やステータス レポート システムなど、時間の経過とともに情報を追加するアプリケーションに特に役立ちます。

二つの空のスライド 同じプレゼンテーションですが、C# コードを使用して 2 番目の空白のスライドが追加されています。

using IronPPT;
using IronPPT.Models;

// Loading an existing presentation file
var ppt = new PresentationDocument("output.pptx");

// Add an additional slide
ppt.AddSlide();

// Save the updated presentation
ppt.Save("output.pptx");
using IronPPT;
using IronPPT.Models;

// Loading an existing presentation file
var ppt = new PresentationDocument("output.pptx");

// Add an additional slide
ppt.AddSlide();

// Save the updated presentation
ppt.Save("output.pptx");
Imports IronPPT
Imports IronPPT.Models

' Loading an existing presentation file
Private ppt = New PresentationDocument("output.pptx")

' Add an additional slide
ppt.AddSlide()

' Save the updated presentation
ppt.Save("output.pptx")
$vbLabelText   $csharpLabel

一貫したレイアウトのためにスライドを複製する

レポートや提案書の作成など、多くのビジネス シナリオでは、同じレイアウト、背景、ロゴやフッターなどのブランド要素を共有する複数のスライドが必要になります。 これらのスライドをそれぞれ手動でコードで作成すると、繰り返し作業になり、保守が困難になります。

より効率的な方法は、プレゼンテーション内に"テンプレート"スライドを作成し、それをプログラムで複製することです。 IronPPT の公開 API では Clone() メソッドが直接存在しませんが、新しいスライドを作成し、テンプレートスライドから望むプロパティと要素をコピーすることで達成できます。テンプレートを使用する際によく用いられる直接的なアプローチは、事前にスライドをデザインし、その後にデータを入力することであり、データ駆動セクションでこれを扱います。 現時点では、これは、生成されたプレゼンテーション全体でデザインの一貫性を維持するための強力な概念を示しており、Syncfusion などの他のライブラリでも見られる機能です。

スライドにリッチコンテンツを追加する最適な方法は何ですか?

スライドが完成したら、次のステップは、意味のあるコンテンツをスライドに挿入することです。 IronPPT は、テキストの追加と書式設定、画像の挿入、図形の描画のための豊富なオブジェクト モデルを提供します。

テキスト、フォント、段落の操作

テキストはあらゆるプレゼンテーションで最も一般的な要素です。 IronPPT では、テキストは Shape (テキストボックスとして機能) 、Paragraph、そして Text というオブジェクト階層によって管理されます。 この構造により、配置とスタイルを細かく制御できます。

最初のスライドにスタイル設定されたタイトルを追加し、2 番目のスライドに箇条書きリストを追加して、2 枚のスライドのプレゼンテーションを拡張してみましょう。

using IronPPT;
using IronPPT.Enums;
using System.Drawing;

// Load the presentation with two slides
var presentation = new PresentationDocument("PresentationWithTwoSlides.pptx");

// --- Modify the First Slide ---
Slide firstSlide = presentation.Slides;

// Clear existing text if any
firstSlide.ClearText();

// Add a title to the first slide. By default, AddText creates a textbox.
// For more control, we can create a Shape and add text to it.
Shape titleShape = firstSlide.AddShape(ShapeType.Rectangle, new Rectangle(50, 50, 860, 100));
titleShape.Fill.SetSolid(new Color("#003B5C")); // A dark blue background
Paragraph titleParagraph = titleShape.AddParagraph("Welcome to IronPPT");
titleParagraph.DefaultTextStyle.SetFont("Arial", 44).SetColor(Color.White).SetBold(true);
titleParagraph.Style.SetAlignment(TextAlignmentTypeValues.Center);

// --- Modify the Second Slide ---
Slide secondSlide = presentation.Slides;
secondSlide.AddText("Key Features", new Rectangle(50, 30, 860, 70))
   .DefaultTextStyle.SetFont("Calibri", 36).SetBold(true);

// Create a shape to act as a textbox for our bulleted list
Shape listShape = secondSlide.AddShape(ShapeType.Rectangle, new Rectangle(70, 120, 800, 300));

// Add a bulleted list
listShape.AddParagraph("Create presentations programmatically").Style.SetBullet(BulletType.Numeric);
listShape.AddParagraph("Add text, images, and shapes").Style.SetBullet(BulletType.Numeric);
listShape.AddParagraph("Style content with fonts, colors, and alignment").Style.SetBullet(BulletType.Numeric);
listShape.AddParagraph("Generate data-driven reports from templates").Style.SetBullet(BulletType.Numeric);

// Style all paragraphs in the list shape
foreach (var para in listShape.Paragraphs)
{
    para.DefaultTextStyle.SetFont("Arial", 28);
    para.Style.SetIndentation(30); // Indent the list
}

// Save the final presentation
presentation.Save("PresentationWithRichContent.pptx");
using IronPPT;
using IronPPT.Enums;
using System.Drawing;

// Load the presentation with two slides
var presentation = new PresentationDocument("PresentationWithTwoSlides.pptx");

// --- Modify the First Slide ---
Slide firstSlide = presentation.Slides;

// Clear existing text if any
firstSlide.ClearText();

// Add a title to the first slide. By default, AddText creates a textbox.
// For more control, we can create a Shape and add text to it.
Shape titleShape = firstSlide.AddShape(ShapeType.Rectangle, new Rectangle(50, 50, 860, 100));
titleShape.Fill.SetSolid(new Color("#003B5C")); // A dark blue background
Paragraph titleParagraph = titleShape.AddParagraph("Welcome to IronPPT");
titleParagraph.DefaultTextStyle.SetFont("Arial", 44).SetColor(Color.White).SetBold(true);
titleParagraph.Style.SetAlignment(TextAlignmentTypeValues.Center);

// --- Modify the Second Slide ---
Slide secondSlide = presentation.Slides;
secondSlide.AddText("Key Features", new Rectangle(50, 30, 860, 70))
   .DefaultTextStyle.SetFont("Calibri", 36).SetBold(true);

// Create a shape to act as a textbox for our bulleted list
Shape listShape = secondSlide.AddShape(ShapeType.Rectangle, new Rectangle(70, 120, 800, 300));

// Add a bulleted list
listShape.AddParagraph("Create presentations programmatically").Style.SetBullet(BulletType.Numeric);
listShape.AddParagraph("Add text, images, and shapes").Style.SetBullet(BulletType.Numeric);
listShape.AddParagraph("Style content with fonts, colors, and alignment").Style.SetBullet(BulletType.Numeric);
listShape.AddParagraph("Generate data-driven reports from templates").Style.SetBullet(BulletType.Numeric);

// Style all paragraphs in the list shape
foreach (var para in listShape.Paragraphs)
{
    para.DefaultTextStyle.SetFont("Arial", 28);
    para.Style.SetIndentation(30); // Indent the list
}

// Save the final presentation
presentation.Save("PresentationWithRichContent.pptx");
Imports IronPPT
Imports IronPPT.Enums
Imports System.Drawing

' Load the presentation with two slides
Private presentation = New PresentationDocument("PresentationWithTwoSlides.pptx")

' --- Modify the First Slide ---
Private firstSlide As Slide = presentation.Slides

' Clear existing text if any
firstSlide.ClearText()

' Add a title to the first slide. By default, AddText creates a textbox.
' For more control, we can create a Shape and add text to it.
Dim titleShape As Shape = firstSlide.AddShape(ShapeType.Rectangle, New Rectangle(50, 50, 860, 100))
titleShape.Fill.SetSolid(New Color("#003B5C")) ' A dark blue background
Dim titleParagraph As Paragraph = titleShape.AddParagraph("Welcome to IronPPT")
titleParagraph.DefaultTextStyle.SetFont("Arial", 44).SetColor(Color.White).SetBold(True)
titleParagraph.Style.SetAlignment(TextAlignmentTypeValues.Center)

' --- Modify the Second Slide ---
Dim secondSlide As Slide = presentation.Slides
secondSlide.AddText("Key Features", New Rectangle(50, 30, 860, 70)).DefaultTextStyle.SetFont("Calibri", 36).SetBold(True)

' Create a shape to act as a textbox for our bulleted list
Dim listShape As Shape = secondSlide.AddShape(ShapeType.Rectangle, New Rectangle(70, 120, 800, 300))

' Add a bulleted list
listShape.AddParagraph("Create presentations programmatically").Style.SetBullet(BulletType.Numeric)
listShape.AddParagraph("Add text, images, and shapes").Style.SetBullet(BulletType.Numeric)
listShape.AddParagraph("Style content with fonts, colors, and alignment").Style.SetBullet(BulletType.Numeric)
listShape.AddParagraph("Generate data-driven reports from templates").Style.SetBullet(BulletType.Numeric)

' Style all paragraphs in the list shape
For Each para In listShape.Paragraphs
	para.DefaultTextStyle.SetFont("Arial", 28)
	para.Style.SetIndentation(30) ' Indent the list
Next para

' Save the final presentation
presentation.Save("PresentationWithRichContent.pptx")
$vbLabelText   $csharpLabel

この例では、いくつかの重要な概念を示します。

  • テキストボックスとしての図形: Shape の型 Rectangle を作成し、テキストのコンテナとして機能させます。 これにより、位置とサイズを正確に制御できます。
  • 段落: テキストコンテンツは Paragraph オブジェクトを通じて追加されます。
  • スタイリング: ParagraphDefaultTextStyle プロパティによりフォント、サイズ、色、ウェイトの流暢なスタイリングが可能になります。 Style プロパティは、配置や箇条書きのような段落レベルのフォーマットを制御します。

テキストとテキストボックスの追加 最初のスライドにはスタイル設定されたタイトルが含まれ、2 番目のスライドには箇条書きのリストが含まれます。

画像の挿入と配置

ロゴ、グラフ、製品画像などの視覚要素は、魅力的なプレゼンテーションに不可欠です。 IronPPT を使用すると、ファイルまたはメモリ ストリームから画像を簡単に追加できます。

次のコードは、タイトル スライドの右下隅に Iron Software のロゴを追加します。

using IronPPT;
using System.Drawing;

var presentation = new PresentationDocument("PresentationWithRichContent.pptx");
Slide firstSlide = presentation.Slides;

// Load an image from a file
Image logo = new Image("iron_logo.png");

// Add the image to the slide and set its properties
var addedImage = firstSlide.AddImage(logo);
addedImage.Position = new Point(750, 450);
addedImage.Width = 150;
addedImage.Height = 75;

presentation.Save("PresentationWithImage.pptx");
using IronPPT;
using System.Drawing;

var presentation = new PresentationDocument("PresentationWithRichContent.pptx");
Slide firstSlide = presentation.Slides;

// Load an image from a file
Image logo = new Image("iron_logo.png");

// Add the image to the slide and set its properties
var addedImage = firstSlide.AddImage(logo);
addedImage.Position = new Point(750, 450);
addedImage.Width = 150;
addedImage.Height = 75;

presentation.Save("PresentationWithImage.pptx");
Imports IronPPT
Imports System.Drawing

Private presentation = New PresentationDocument("PresentationWithRichContent.pptx")
Private firstSlide As Slide = presentation.Slides

' Load an image from a file
Private logo As New Image("iron_logo.png")

' Add the image to the slide and set its properties
Private addedImage = firstSlide.AddImage(logo)
addedImage.Position = New Point(750, 450)
addedImage.Width = 150
addedImage.Height = 75

presentation.Save("PresentationWithImage.pptx")
$vbLabelText   $csharpLabel

AddImage メソッドは、スライドに追加された後に Height、回転 (Angle) をさらに操作できる Image オブジェクトを返します。

最初のスライドに画像を追加 タイトル スライドの右下隅に画像が追加されました。

図形の描画とカスタマイズ

テキスト ボックスに使用される長方形以外にも、IronPPT ではさまざまな図形を描画して、スライドに視覚的な構造と強調を加えることができます。 ジオメトリ、色、位置を制御できます。

コンテンツを視覚的に分離するために、2 番目のスライドに装飾的な図形を追加しましょう。

using IronPPT;
using IronPPT.Enums;
using System.Drawing;

var presentation = new PresentationDocument("PresentationWithImage.pptx");
Slide secondSlide = presentation.Slides;

// Add a circle shape to the second slide
Shape circle = secondSlide.AddShape(ShapeType.Ellipse, new Rectangle(400, 250, 200, 200));
circle.Name = "DecorativeCircle";

// Customize the shape's appearance
circle.Fill.SetSolid(new Color("#E0F7FA")); // A light cyan color
circle.Outline.SetColor(new Color("#00796B")).SetWidth(3); // A teal outline

presentation.Save("PresentationWithShapes.pptx");
using IronPPT;
using IronPPT.Enums;
using System.Drawing;

var presentation = new PresentationDocument("PresentationWithImage.pptx");
Slide secondSlide = presentation.Slides;

// Add a circle shape to the second slide
Shape circle = secondSlide.AddShape(ShapeType.Ellipse, new Rectangle(400, 250, 200, 200));
circle.Name = "DecorativeCircle";

// Customize the shape's appearance
circle.Fill.SetSolid(new Color("#E0F7FA")); // A light cyan color
circle.Outline.SetColor(new Color("#00796B")).SetWidth(3); // A teal outline

presentation.Save("PresentationWithShapes.pptx");
Imports IronPPT
Imports IronPPT.Enums
Imports System.Drawing

Private presentation = New PresentationDocument("PresentationWithImage.pptx")
Private secondSlide As Slide = presentation.Slides

' Add a circle shape to the second slide
Private circle As Shape = secondSlide.AddShape(ShapeType.Ellipse, New Rectangle(400, 250, 200, 200))
circle.Name = "DecorativeCircle"

' Customize the shape's appearance
circle.Fill.SetSolid(New Color("#E0F7FA")) ' A light cyan color
circle.Outline.SetColor(New Color("#00796B")).SetWidth(3) ' A teal outline

presentation.Save("PresentationWithShapes.pptx")
$vbLabelText   $csharpLabel

このコードは、淡いシアン色の塗りつぶしと青緑色のアウトラインを持つ円を追加します。プログラムで図形を追加し、スタイルを設定できる機能は、カスタム図やフローチャートを作成したり、自動化されたプレゼンテーションのビジュアルデザインを強化したりする際に非常に役立ちます。

スタイル付きの円 2 番目のスライドには、C# コードで追加されたスタイル設定された円が表示されます。

データ駆動型のプレゼンテーションを作成するにはどうすればよいでしょうか?

PowerPoint 自動化の真の力は、動的なデータ ソースからプレゼンテーションを生成することにあります。 ここで IronPPT が優れた点となり、表やグラフを作成したり、テンプレートを即座に作成したりできる高度なレポート システムを構築できるようになります。 この機能により、基本的なライブラリとは一線を画し、データ駆動型機能も重視する Aspose や Syncfusion などのツールの強力な競合相手としての地位を確立しています。

動的レポートのテンプレートの使用

最も効果的なワークフローの 1 つは、定義済みのレイアウトとプレースホルダー テキストを含むマスター PowerPoint テンプレートを作成することです。 C# アプリケーションはこのテンプレートを読み込み、プレースホルダーをデータベース、API、またはその他のソースからのデータに置き換えることができます。

ステップ1: PowerPointテンプレートを作成する

最初に、ReportTemplate.pptx という名前の PowerPoint ファイルを作成します。 スライド上に {{TotalSales}} などの固有のプレースホルダ文字列を持つテキストボックスを追加します。

ステップ2: C#でテンプレートを埋める

次のコードは、このテンプレートを読み込み、データを定義し、スライド上の図形を反復処理してテキストの置換を実行する方法を示しています。

using IronPPT;
using System.Collections.Generic;

// --- Sample Data ---
var reportData = new Dictionary<string, string>
{
    { "{{ClientName}}", "Global Tech Inc." },
    { "{{ReportDate}}", System.DateTime.Now.ToShortDateString() },
    { "{{TotalSales}}", "$1,250,000" },
    { "{{PreparedBy}}", "Automated Reporting System" }
};

// Load the presentation template
var presentation = new PresentationDocument("ReportTemplate.pptx");
Slide reportSlide = presentation.Slides;

// Iterate through all shapes on the slide to find and replace text
foreach (var shape in reportSlide.Shapes)
{
    // Iterate through all paragraphs within the shape
    foreach (var paragraph in shape.Paragraphs)
    {
        // Iterate through all text runs in the paragraph
        foreach (var textRun in paragraph.Texts)
        {
            foreach (var kvp in reportData)
            {
                if (textRun.Value.Contains(kvp.Key))
                - textRun.ReplaceText(kvp.Key, kvp.Value);
            }
        }
    }
}

// Save the generated report
presentation.Save("GeneratedClientReport.pptx");
using IronPPT;
using System.Collections.Generic;

// --- Sample Data ---
var reportData = new Dictionary<string, string>
{
    { "{{ClientName}}", "Global Tech Inc." },
    { "{{ReportDate}}", System.DateTime.Now.ToShortDateString() },
    { "{{TotalSales}}", "$1,250,000" },
    { "{{PreparedBy}}", "Automated Reporting System" }
};

// Load the presentation template
var presentation = new PresentationDocument("ReportTemplate.pptx");
Slide reportSlide = presentation.Slides;

// Iterate through all shapes on the slide to find and replace text
foreach (var shape in reportSlide.Shapes)
{
    // Iterate through all paragraphs within the shape
    foreach (var paragraph in shape.Paragraphs)
    {
        // Iterate through all text runs in the paragraph
        foreach (var textRun in paragraph.Texts)
        {
            foreach (var kvp in reportData)
            {
                if (textRun.Value.Contains(kvp.Key))
                - textRun.ReplaceText(kvp.Key, kvp.Value);
            }
        }
    }
}

// Save the generated report
presentation.Save("GeneratedClientReport.pptx");
Imports System
Imports IronPPT
Imports System.Collections.Generic

' --- Sample Data ---
Private reportData = New Dictionary(Of String, String) From {
	{"{{ClientName}}", "Global Tech Inc."},
	{"{{ReportDate}}", DateTime.Now.ToShortDateString()},
	{"{{TotalSales}}", "$1,250,000"},
	{"{{PreparedBy}}", "Automated Reporting System"}
}

' Load the presentation template
Private presentation = New PresentationDocument("ReportTemplate.pptx")
Private reportSlide As Slide = presentation.Slides

' Iterate through all shapes on the slide to find and replace text
For Each shape In reportSlide.Shapes
	' Iterate through all paragraphs within the shape
	For Each paragraph In shape.Paragraphs
		' Iterate through all text runs in the paragraph
		For Each textRun In paragraph.Texts
			For Each kvp In reportData
				If textRun.Value.Contains(kvp.Key) Then
				- textRun.ReplaceText(kvp.Key, kvp.Value)
				End If
			Next kvp
		Next textRun
	Next paragraph
Next shape

' Save the generated report
presentation.Save("GeneratedClientReport.pptx")
$vbLabelText   $csharpLabel

このテンプレートベースのアプローチは非常に強力です。 デザインとデータを分離することで、デザイナーはコードを変更することなく PowerPoint のテンプレートの外観と操作性を変更できます。

データコレクションからのテーブルの生成

表形式のデータの表示は、ほとんどのビジネス レポートの中心的な要件です。 IronPPT は、C# データ構造 List<t> などから直接プログラムでテーブルを作成してデータを入力することができます。

例えば、単純な Product クラスと製品リストがあるとします。 次のコードは、このデータを表示するテーブルを含む新しいスライドを生成します。

// --- Sample Data Model and Collection ---
public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int StockLevel { get; set; }
}

var products = new List<Product>
{
    new Product { ID = 101, Name = "Quantum CPU", Price = 299.99m, StockLevel = 50 },
    new Product { ID = 205, Name = "Photon SSD", Price = 149.50m, StockLevel = 120 },
    new Product { ID = 310, Name = "Gravity GPU", Price = 799.00m, StockLevel = 25 }
};

// --- Table Generation ---
var presentation = new PresentationDocument();
var tableSlide = presentation.AddSlide();
tableSlide.AddText("Product Inventory Report", new Rectangle(50, 20, 860, 50))
   .DefaultTextStyle.SetFont("Arial", 32).SetBold(true);

// Add a table to the slide with 4 columns and (N+1) rows
Table productTable = tableSlide.AddTable(products.Count + 1, 4, new Rectangle(50, 100, 860, 300));

// --- Populate Header Row ---
productTable.Rows.Cells.TextBody.AddParagraph("Product ID");
productTable.Rows.Cells.TextBody.AddParagraph("Product Name");
productTable.Rows.Cells.TextBody.AddParagraph("Price");
productTable.Rows.Cells.TextBody.AddParagraph("Stock");

// Style the header row
foreach (var cell in productTable.Rows.Cells)
{
    cell.Fill.SetSolid(new Color("#4A5568")); // Dark Gray
    cell.TextBody.Paragraphs.DefaultTextStyle.SetColor(Color.White).SetBold(true);
    cell.TextBody.Paragraphs.Style.SetAlignment(TextAlignmentTypeValues.Center);
}

// --- Populate Data Rows ---
for (int i = 0; i < products.Count; i++)
{
    var product = products[i];
    productTable.Rows[i + 1].Cells.TextBody.AddParagraph(product.ID.ToString());
    productTable.Rows[i + 1].Cells.TextBody.AddParagraph(product.Name);
    productTable.Rows[i + 1].Cells.TextBody.AddParagraph(product.Price.ToString("C"));
    productTable.Rows[i + 1].Cells.TextBody.AddParagraph(product.StockLevel.ToString());
}

presentation.Save("ProductInventoryReport.pptx");
// --- Sample Data Model and Collection ---
public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int StockLevel { get; set; }
}

var products = new List<Product>
{
    new Product { ID = 101, Name = "Quantum CPU", Price = 299.99m, StockLevel = 50 },
    new Product { ID = 205, Name = "Photon SSD", Price = 149.50m, StockLevel = 120 },
    new Product { ID = 310, Name = "Gravity GPU", Price = 799.00m, StockLevel = 25 }
};

// --- Table Generation ---
var presentation = new PresentationDocument();
var tableSlide = presentation.AddSlide();
tableSlide.AddText("Product Inventory Report", new Rectangle(50, 20, 860, 50))
   .DefaultTextStyle.SetFont("Arial", 32).SetBold(true);

// Add a table to the slide with 4 columns and (N+1) rows
Table productTable = tableSlide.AddTable(products.Count + 1, 4, new Rectangle(50, 100, 860, 300));

// --- Populate Header Row ---
productTable.Rows.Cells.TextBody.AddParagraph("Product ID");
productTable.Rows.Cells.TextBody.AddParagraph("Product Name");
productTable.Rows.Cells.TextBody.AddParagraph("Price");
productTable.Rows.Cells.TextBody.AddParagraph("Stock");

// Style the header row
foreach (var cell in productTable.Rows.Cells)
{
    cell.Fill.SetSolid(new Color("#4A5568")); // Dark Gray
    cell.TextBody.Paragraphs.DefaultTextStyle.SetColor(Color.White).SetBold(true);
    cell.TextBody.Paragraphs.Style.SetAlignment(TextAlignmentTypeValues.Center);
}

// --- Populate Data Rows ---
for (int i = 0; i < products.Count; i++)
{
    var product = products[i];
    productTable.Rows[i + 1].Cells.TextBody.AddParagraph(product.ID.ToString());
    productTable.Rows[i + 1].Cells.TextBody.AddParagraph(product.Name);
    productTable.Rows[i + 1].Cells.TextBody.AddParagraph(product.Price.ToString("C"));
    productTable.Rows[i + 1].Cells.TextBody.AddParagraph(product.StockLevel.ToString());
}

presentation.Save("ProductInventoryReport.pptx");
' --- Sample Data Model and Collection ---
Public Class Product
	Public Property ID() As Integer
	Public Property Name() As String
	Public Property Price() As Decimal
	Public Property StockLevel() As Integer
End Class

Private products = New List(Of Product) From {
	New Product With {
		.ID = 101,
		.Name = "Quantum CPU",
		.Price = 299.99D,
		.StockLevel = 50
	},
	New Product With {
		.ID = 205,
		.Name = "Photon SSD",
		.Price = 149.50D,
		.StockLevel = 120
	},
	New Product With {
		.ID = 310,
		.Name = "Gravity GPU",
		.Price = 799.00D,
		.StockLevel = 25
	}
}

' --- Table Generation ---
Private presentation = New PresentationDocument()
Private tableSlide = presentation.AddSlide()
tableSlide.AddText("Product Inventory Report", New Rectangle(50, 20, 860, 50)).DefaultTextStyle.SetFont("Arial", 32).SetBold(True)

' Add a table to the slide with 4 columns and (N+1) rows
Dim productTable As Table = tableSlide.AddTable(products.Count + 1, 4, New Rectangle(50, 100, 860, 300))

' --- Populate Header Row ---
productTable.Rows.Cells.TextBody.AddParagraph("Product ID")
productTable.Rows.Cells.TextBody.AddParagraph("Product Name")
productTable.Rows.Cells.TextBody.AddParagraph("Price")
productTable.Rows.Cells.TextBody.AddParagraph("Stock")

' Style the header row
For Each cell In productTable.Rows.Cells
	cell.Fill.SetSolid(New Color("#4A5568")) ' Dark Gray
	cell.TextBody.Paragraphs.DefaultTextStyle.SetColor(Color.White).SetBold(True)
	cell.TextBody.Paragraphs.Style.SetAlignment(TextAlignmentTypeValues.Center)
Next cell

' --- Populate Data Rows ---
For i As Integer = 0 To products.Count - 1
	Dim product = products(i)
	productTable.Rows(i + 1).Cells.TextBody.AddParagraph(product.ID.ToString())
	productTable.Rows(i + 1).Cells.TextBody.AddParagraph(product.Name)
	productTable.Rows(i + 1).Cells.TextBody.AddParagraph(product.Price.ToString("C"))
	productTable.Rows(i + 1).Cells.TextBody.AddParagraph(product.StockLevel.ToString())
Next i

presentation.Save("ProductInventoryReport.pptx")
$vbLabelText   $csharpLabel

データを視覚化するためのチャートの追加

データをより理解しやすくするには、グラフが不可欠です。 IronPPT は、データを効果的に視覚化するために、さまざまな種類のグラフの追加と入力をサポートしています。

この例では、製品リストからの在庫レベルを視覚化する棒グラフを作成します。

using IronPPT.Charts;
using IronPPT.Enums;

// --- Chart Generation ---
var presentation = new PresentationDocument();
var chartSlide = presentation.AddSlide();
chartSlide.AddText("Product Stock Levels", new Rectangle(50, 20, 860, 50))
   .DefaultTextStyle.SetFont("Arial", 32).SetBold(true);

// Add a bar chart to the slide
Chart stockChart = chartSlide.AddChart(ChartType.Bar, new Rectangle(100, 100, 750, 450));
stockChart.Title.Text = "Current Inventory";

// Get the chart data object to populate it
ChartData chartData = stockChart.ChartData;
chartData.Categories.Clear(); // Clear default categories
chartData.Series.Clear();     // Clear default series

// Add a series for our stock data
var series = chartData.Series.Add("Stock Level");

// Populate categories (product names) and data points (stock levels)
foreach (var product in products)
{
    chartData.Categories.Add(product.Name);
    series.DataPoints.Add(product.StockLevel);
}

presentation.Save("ProductStockChart.pptx");
using IronPPT.Charts;
using IronPPT.Enums;

// --- Chart Generation ---
var presentation = new PresentationDocument();
var chartSlide = presentation.AddSlide();
chartSlide.AddText("Product Stock Levels", new Rectangle(50, 20, 860, 50))
   .DefaultTextStyle.SetFont("Arial", 32).SetBold(true);

// Add a bar chart to the slide
Chart stockChart = chartSlide.AddChart(ChartType.Bar, new Rectangle(100, 100, 750, 450));
stockChart.Title.Text = "Current Inventory";

// Get the chart data object to populate it
ChartData chartData = stockChart.ChartData;
chartData.Categories.Clear(); // Clear default categories
chartData.Series.Clear();     // Clear default series

// Add a series for our stock data
var series = chartData.Series.Add("Stock Level");

// Populate categories (product names) and data points (stock levels)
foreach (var product in products)
{
    chartData.Categories.Add(product.Name);
    series.DataPoints.Add(product.StockLevel);
}

presentation.Save("ProductStockChart.pptx");
Imports IronPPT.Charts
Imports IronPPT.Enums

' --- Chart Generation ---
Private presentation = New PresentationDocument()
Private chartSlide = presentation.AddSlide()
chartSlide.AddText("Product Stock Levels", New Rectangle(50, 20, 860, 50)).DefaultTextStyle.SetFont("Arial", 32).SetBold(True)

' Add a bar chart to the slide
Dim stockChart As Chart = chartSlide.AddChart(ChartType.Bar, New Rectangle(100, 100, 750, 450))
stockChart.Title.Text = "Current Inventory"

' Get the chart data object to populate it
Dim chartData As ChartData = stockChart.ChartData
chartData.Categories.Clear() ' Clear default categories
chartData.Series.Clear() ' Clear default series

' Add a series for our stock data
Dim series = chartData.Series.Add("Stock Level")

' Populate categories (product names) and data points (stock levels)
For Each product In products
	chartData.Categories.Add(product.Name)
	series.DataPoints.Add(product.StockLevel)
Next product

presentation.Save("ProductStockChart.pptx")
$vbLabelText   $csharpLabel

このコードは、C# オブジェクトから動的に入力されたプロフェッショナルな外観の棒グラフを生成し、手動による介入なしにデータを明確に視覚的に表現します。

Office Interop ではなく専用ライブラリを選択する理由

プログラムによる PowerPoint 作成を検討している開発者にとって、選択は多くの場合、Microsoft Office Interop を使用するか、IronPPT などの専用のサードパーティ ライブラリを使用するかということになります。 Office ライセンスをお持ちの場合、Interop は"無料"ですが、最新のサーバー側アプリケーションの要求に合わせて設計されたものではありません。 次の表に重要な違いの概要を示します。

機能 / 考慮事項 IronPPT for .NET Microsoft.Office.Interop.PowerPoint
サーバー側の依存性 なし。 100%管理された.NETライブラリ。 サーバーに Microsoft Office がインストールされている必要があります。
パフォーマンスとスケーラビリティ マルチスレッド、高パフォーマンスの使用向けに最適化されています。 サーバー側での使用向けに設計されていません。 遅くなり、不安定になる可能性があります。
展開の複雑さ シンプルな NuGet パッケージのインストール。 複雑な COM 依存関係、アクセス許可、および Office ライセンス。
プラットフォームサポート Windows、Linux、macOS、Docker、Azure、AWS。 Windowsのみ。 最新のクロスプラットフォーム展開には適していません。
API設計と使いやすさ 開発者向けに設計された、モダンで直感的で流暢な API。 古くて冗長で複雑な COM ベースの API。
安定性 無人実行でも安定して信頼性があります。 サーバー環境ではプロセスのハングやメモリ リークが発生しやすくなります。

IronPPT のような専用ライブラリを選択すると、開発が高速化され、安定性が向上し、メンテナンスのオーバーヘッドが低減し、あらゆるプラットフォームに展開できる柔軟性が得られます。 それは、技術負債とInteropの制限を回避する強固でモダンなアーキテクチャへの投資です。IronPPTのような専用ライブラリを選ぶことで、より高速な開発、より高い安定性、低い維持費用、およびあらゆるプラットフォームへのデプロイの柔軟性が得られます。 これは、Interop の技術的負債と制限を回避する、堅牢で最新のアーキテクチャへの投資です。

エンタープライズPowerPoint自動化のベストプラクティス

本番環境レベルのアプリケーションを構築する場合、ベスト プラクティスに従うことで、コードの効率性、保守性、回復力を確保できます。

1.大規模プレゼンテーションのパフォーマンスを最適化する:スライド数が多いプレゼンテーションや大きな画像を含むプレゼンテーションでは、メモリ使用量に注意してください。 可能であればストリームから画像をロードし、TextStyle または ParagraphStyle のようなオブジェクトを再利用し、各要素ごとに新しいインスタンスを作成するのではなく再利用してください。 2.一貫性のあるデザインを維持する:テンプレートとヘルパーメソッドを活用して、デザインの一貫性を確保します。 ヘッダー、本文テキスト、キャプション用に事前に設定された TextStyleParagraphStyle オブジェクトを返すメソッドを持つ静的クラスを作成します。 これにより、ブランドの一貫性が確保され、グローバルなスタイルの変更が容易になります。 3.エラーと例外を適切に処理する:ファイル入出力や外部依存関係が失敗する可能性があります。 常に try-catch ブロック内でプレゼンテーション生成ロジックをラップし、FileNotFoundException やアクセス許可エラーのような潜在的な例外を処理してください。

以下は、ファイルを保存する際の堅牢なエラー処理の簡単な例です。

try
{
    // All presentation creation logic here...
    var presentation = new PresentationDocument();
    presentation.AddSlide().AddText("Final Report");

    // Attempt to save the presentation
    presentation.Save("C:\\ProtectedFolder\\FinalReport.pptx");
}
catch (System.IO.IOException ex)
{
    // Log the specific I/O error
    Console.WriteLine($"Error saving file: {ex.Message}");
    // Potentially try saving to a fallback location
}
catch (System.UnauthorizedAccessException ex)
{
    // Log the permission error
    Console.WriteLine($"Permission denied. Cannot save file. {ex.Message}");
}
catch (Exception ex)
{
    // Catch any other unexpected errors
    Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
try
{
    // All presentation creation logic here...
    var presentation = new PresentationDocument();
    presentation.AddSlide().AddText("Final Report");

    // Attempt to save the presentation
    presentation.Save("C:\\ProtectedFolder\\FinalReport.pptx");
}
catch (System.IO.IOException ex)
{
    // Log the specific I/O error
    Console.WriteLine($"Error saving file: {ex.Message}");
    // Potentially try saving to a fallback location
}
catch (System.UnauthorizedAccessException ex)
{
    // Log the permission error
    Console.WriteLine($"Permission denied. Cannot save file. {ex.Message}");
}
catch (Exception ex)
{
    // Catch any other unexpected errors
    Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
Try
	' All presentation creation logic here...
	Dim presentation = New PresentationDocument()
	presentation.AddSlide().AddText("Final Report")

	' Attempt to save the presentation
	presentation.Save("C:\ProtectedFolder\FinalReport.pptx")
Catch ex As System.IO.IOException
	' Log the specific I/O error
	Console.WriteLine($"Error saving file: {ex.Message}")
	' Potentially try saving to a fallback location
Catch ex As System.UnauthorizedAccessException
	' Log the permission error
	Console.WriteLine($"Permission denied. Cannot save file. {ex.Message}")
Catch ex As Exception
	' Catch any other unexpected errors
	Console.WriteLine($"An unexpected error occurred: {ex.Message}")
End Try
$vbLabelText   $csharpLabel

結論と次のステップ

C# で PowerPoint プレゼンテーションの作成を自動化すると、生産性が大幅に向上し、強力な新しいアプリケーション機能が有効になります。 これまで見てきたように、IronPPT for .NETは、従来のOffice Interopメソッドの能力と安定性をはるかに超える直感的でモダンでクロスプラットフォームのソリューションを提供します。 シンプルなスライドの作成から、表やグラフを使用した複雑なデータ駆動型レポートの作成まで、IronPPT は作業を効率的に完了するためのツールを提供します。

プロジェクトに他のドキュメント形式の操作も含まれる場合は、 Iron Suite全体を検討することを検討してください。 PDF 操作用の IronPDF、Excel スプレッドシート用の IronXL、バーコード読み取り用の IronBarcode などのライブラリを使用すると、一貫性のある高品質のツール セットですべてのドキュメント処理ニーズに対応できます。

自動化を始める準備はできましたか? IronPPT のパワーをフルに体験する最良の方法は、自分のプロジェクトで試してみることです。

今IronPPTを始めましょう。
green arrow pointer

さらに詳しい情報については、公式のIronPPT ドキュメントを参照するか、 API リファレンスのクラスとメソッドを詳しく調べてください。

ご注意Asposeは、各所有者の登録商標です。)] このサイトはAsposeに関連していませんし、認可もされていません、またスポンサーも受けていません。 すべての製品名、ロゴ、およびブランドは各所有者の所有物です。 比較は情報提供のみを目的としており、執筆時点で公開されている情報を反映しています。

よくある質問

C#でPowerPointプレゼンテーションを自動化する方法は?

IronPPT for .NETを使用してPowerPointプレゼンテーションを自動化できます。このライブラリでは、Microsoft Office Interopに依存せずに、プログラム的にスライドを作成、編集、および操作できます。

.NETライブラリを使用してMicrosoft Office InteropよりもPowerPointの自動化を行う利点は何ですか?

IronPPTのような.NETライブラリを使用することで、安定性、クロスプラットフォーム互換性が得られ、Microsoft Officeのライセンスインストールが不要になるため、サーバーやコンテナ環境に最適です。

C#を使用してPowerPointプレゼンテーションに新しいスライドを追加する方法は?

IronPPT を使用すると、new PresentationDocument() でプレゼンテーションを初期化した後、AddSlide() メソッドを使用して新しいスライドを追加できます。

プログラム的にPowerPointプレゼンテーションで既存のスライドをクローンできますか?

はい、IronPPT では Slides コレクションにアクセスし、スライドコンテンツを効率的に複製するためのメソッドを使用してスライドをクローンできます。

C#でPowerPointスライドにスタイル付きテキストを挿入する方法は?

IronPPT は、スライドにテキストを挿入およびフォーマットするための AddText()SetFont()SetColor() などのメソッドやテキストスタイルオプションを提供します。

C#でPowerPointスライドに画像を追加するプロセスは?

画像を new Image() を使ってロードし、slide.AddImage() を使用してスライドに追加し、プログラムでその位置とサイズを設定できます。

テンプレートを使用してデータ駆動のPowerPointプレゼンテーションを作成する方法は?

IronPPT は、プレースホルダーを含むテンプレートをロードすることをサポートしており、ReplaceText() などのメソッドを使用して動的データに置き換えることができ、自動的にレポートを生成します。

C#を使ったPowerPointの自動化におけるエラーハンドリングのベストプラクティスは何ですか?

自動化コードを try-catch ブロックでラップして、IOExceptionUnauthorizedAccessException のような例外を処理します。エラーを記録することでデバッグの助けになり、堅牢な自動化を確保できます。

C#コレクションのデータを使用してPowerPointスライドにテーブルを作成する方法は?

IronPPT の AddTable() メソッドを使用してテーブルを作成し、C# コレクションからデータをポピュレートし、TextBody.Paragraphs.DefaultTextStyle を介して各セルの外観をカスタマイズします。

IronPPTはクロスプラットフォームのPowerPoint自動化ソリューションの開発に適していますか?

はい、IronPPTはWindows、Linux、macOSを含むさまざまなプラットフォームで動作し、Dockerコンテナでの展開もサポートしているため、クロスプラットフォームアプリケーションに最適です。

Jacob Mellor、Ironチームの最高技術責任者(CTO)
最高技術責任者(CTO)

ジェイコブ・メラーはIron Softwareの最高技術責任者(CTO)であり、C# PDFテクノロジーを開拓する先見的なエンジニアです。Iron Softwareのコアコードベースを支えるオリジナル開発者として、彼は創業以来、会社の製品アーキテクチャを形成し、CEOのCameron Rimingtonとともに、会社をNASA、Tesla、および世界的な政府機関にサービスを提供する50人以上の会社に変えました。1999年にロンドンで最初のソフトウェアビジネスを開業し、2005年に最初 for .NETコンポーネントを作成した後、Microsoftのエコシステム全体で複雑な問題を解決することを専門としました。

彼の主要なIronPDFとIron Suite .NETライブラリは、世界中で3000万以上のNuGetインストールを達成し、彼の基礎となるコードは世界中で使用されている開発者ツールに力を与え続けています。25年の商業経験と41年のコーディングの専門知識を持つJacobは、次世代の技術リーダーを指導しながら、エンタープライズグレードのC#、Java、Python PDFテクノロジーにおけるイノベーションの推進に注力しています。

アイアンサポートチーム

私たちは週5日、24時間オンラインで対応しています。
チャット
メール
電話してね