跳過到頁腳內容
PPT 工具
如何使用 C# 製作 PowerPoint 簡報

如何以 C# 程式化方式建立並自動化 PowerPoint 簡報

每週手動建立相同的 PowerPoint 簡報是一項繁瑣且容易出錯的任務,沒有任何開發人員喜歡做這項工作。 無論是產生每週銷售報告、每月財務摘要,還是個人化客戶提案,這些流程都非常適合自動化。 多年來,.NET 領域的首選解決方案是 Microsoft Office Interop,這項技術允許以程式方式控制 Office 應用程式。 然而,這種方法有一些明顯的缺點:它需要在伺服器上安裝授權版本的 Microsoft Office,在伺服器環境中穩定性很差,並且完全排除了在 Linux、macOS 或 Docker 容器中進行現代跨平台部署的可能性。

幸運的是,還有更好的方法。 本教學將向您展示如何使用 IronPPT for.NET(一個專為現代開發而構建的強大而輕量級的庫)在 C# 中以程式設計方式建立 PowerPoint 簡報。 我們將探索如何實現從創建簡單的幻燈片到使用模板生成複雜的、數據驅動的簡報(包括表格和圖表)的所有自動化操作。 借助 IronPPT,您可以建立快速、可擴展且可靠的簡報自動化工作流程,這些工作流程可以在任何地方運行,而無需依賴 Microsoft Office。

IronPPT - C#簡報庫 IronPPT for .NET 程式庫讓開發人員可以使用 C# 以程式設計方式建立和管理 PowerPoint 檔案。

如何使用 C# 產生 PowerPoint 文件?

使用 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的新檔案。 開啟後將顯示一張包含您新增的文字的幻燈片。 這個簡單的範例示範了建立簡報物件、新增內容和保存檔案的基本工作流程。

使用 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# 程式碼添加了第二張空白幻燈片。

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 (作為文字方塊)、 ParagraphText 。 這種結構可以對定位和樣式進行精細控制。

讓我們在兩張投影片的簡報基礎上進行擴展,在第一張投影片上新增一個樣式標題,在第二張投影片上新增一個項目符號清單。

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

這個例子展示了幾個關鍵概念:

-將形狀用作文字方塊:我們建立一個Rectangle Shape作為文字的容器。 這使我們能夠精確控制它的位置和大小。 -段落:文字內容透過Paragraph物件添加。 -樣式: ParagraphDefaultTextStyle屬性允許對字體、大小、顏色和粗細進行流暢的樣式設定。 Style屬性控制段落層級的格式設置,例如對齊方式和項目符號。

新增文字和文字框 第一張投影片現在新增了樣式標題,第二張投影片包含項目符號清單。

插入和定位影像

標誌、圖表和產品圖片等視覺元素對於吸引人的簡報至關重要。 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方法傳回Image對象,讓您在將其新增至投影片後進一步操作其PositionWidthHeight和旋轉( Angle )。

在第一張投影片中新增圖片 標題投影片現在包含一張位於右下角的圖片。

繪製和自訂形狀

除了用於文字方塊的矩形之外,IronPPT 還可以繪製各種形狀,為您的投影片添加視覺結構和重點。 您可以控制它們的幾何形狀、顏色和位置。

讓我們在第二張投影片中加入一個裝飾性形狀,以便在視覺上分隔內容。

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

這段程式碼增加了一個淺青色填滿、藍綠色輪廓的圓形。能夠以程式設計方式新增和設定形狀樣式,對於建立自訂圖表、流程圖,或只是增強自動化簡報的視覺設計都至關重要。

一個風格化的圓圈 第二張幻燈片現在添加了一個樣式化的圓形,該圓形是透過 C# 代碼添加的。

如何建立數據驅動型簡報?

PowerPoint自動化的真正強大之處在於能夠利用動態資料來源產生簡報。 IronPPT 的優點就在於此,它能讓你建立複雜的報表系統,即時建立表格、圖表並填入範本。 這項功能使其區別於基本函式庫,並使其成為 Aspose 和 Syncfusion 等工具的有力競爭對手,這些工具也強調資料驅動功能。

使用範本建立動態報表

最有效的工作流程之一是建立一個具有預先定義佈局和占位符文字的主 PowerPoint 範本。 然後,您的 C# 應用程式可以載入此模板,並將佔位符替換為來自資料庫、API 或任何其他來源的資料。

步驟 1:建立 PowerPoint 模板

首先,建立一個名為ReportTemplate.pptx的 PowerPoint 檔案。 在投影片上,新增帶有唯一佔位符字串的文字方塊,例如{{ClientName}}{{ReportDate}}{{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建立和填入表格。 List

假設我們有一個簡單的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 程式庫。 需要在伺服器上安裝微軟Office。
效能與可擴展性 針對多執行緒、高效能應用進行了最佳化。 並非設計用於伺服器端; 速度可能較慢且不穩定。
部署複雜性 簡單的 NuGet 套件安裝。 複雜的 COM 依賴關係、權限和 Office 授權。
平台支援 Windows、Linux、macOS、Docker、Azure、AWS。 僅限Windows系統。 不適用於現代跨平台部署。
API設計及易用性 專為開發者設計的現代化、直覺、流暢的 API。 老舊、冗長且複雜的基於 COM 的 API。
穩定 穩定可靠,可無人值守執行。 伺服器環境下容易出現進程掛起和記憶體洩漏。

選擇像 IronPPT 這樣的專用函式庫意味著更快的開發速度、更高的穩定性、更低的維護成本以及在任何平台上部署的靈活性。 這是對穩健、現代架構的投資,它避免了互通性的技術債和限制。選擇像 IronPPT 這樣的專用函式庫意味著更快的開發速度、更高的穩定性、更低的維護成本以及在任何平台上靈活部署的能力。 這是對強大、現代架構的投資,避免了互通性的技術債和限制。

企業級 PowerPoint 自動化最佳實踐

在建立生產級應用程式時,遵循最佳實踐可以確保程式碼高效、易於維護且具有彈性。

1.最佳化大型簡報的效能:對於包含大量投影片或大型影像的簡報,請注意記憶體使用情況。 盡可能從流中載入圖像,並重複使用TextStyleParagraphStyle等對象,而不是為每個元素建立新實例。 2.保持設計一致性:利用範本和輔助方法來強制執行設計一致性。 建立一個靜態類,其中包含傳回預先配置的TextStyleParagraphStyle物件的方法,這些物件分別用於標題、正文和說明文字。 這確保了品牌的一致性,並使全球風格變更變得輕而易舉。 3.優雅地處理錯誤和異常:檔案 I/O 和外部依賴項可能會失敗。 始終將簡報產生邏輯放在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 。 借助 IronPDF(用於 PDF 處理)、IronXL(用於 Excel 試算表)和 IronBarcode(用於讀取條碼)等庫,您可以使用一套一致、高品質的工具來滿足所有文件處理需求。

準備好開始自動化了嗎? 體驗 IronPPT 全部功能的最佳方法是在您自己的專案中嘗試使用它。

!{--01001100010010010100001001010010010000010101001001011001010 111110100011101000101010101010001011111010100110101010001000001 010100100101010001000101010001000101111101010111010010010101010 001001000010111110101000001010101000010010000101111101010000010 1001001001111010001000101010101000011010101010001011111010101000101001001001001010101010001010010010010010100001010101010101 010101011000010101000100010101001110010001000101010001000101111101000010010011000100111110100010010011000100111100

如需了解更多詳細信息,您可以瀏覽IronPPT 官方文件或深入了解API 參考中的類別和方法。

Aspose 是其各自所有者的註冊商標。 本網站與 Aspose 公司沒有任何關聯,也未獲得 Aspose 的認可或贊助。 所有產品名稱、標誌和品牌均為其各自所有者的財產。 文中比較僅供參考,反映的是撰寫本文時公開可取得的資訊。

常見問題解答

如何用 C# 自動化 PowerPoint 簡報?

您可以使用 IronPPT for .NET 來自動化 PowerPoint 簡報。這個函式庫可讓您以程式化的方式建立、編輯和處理幻燈片,而無需依賴 Microsoft Office Interop。

在 PowerPoint 自動化方面,使用 .NET 函式庫比 Microsoft Office Interop 有哪些優勢?

使用 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 等異常。記錄錯誤有助於除錯並確保穩健的自動化。

如何在 PowerPoint 投影片中使用 C# 集合的資料建立表格?

使用 IronPPT 的 AddTable() 方法來建立表格,然後以 C# 集合中的資料來填充表格,透過 TextBody.Paragraphs.DefaultTextStyle 來自訂每個儲存格的外觀。

IronPPT 是否適合開發跨平台的 PowerPoint 自動化解決方案?

是的,IronPPT 可在各種平台上執行,包括 Windows、Linux 和 macOS,並支援在 Docker 容器中部署,因此非常適合跨平台應用程式。

Jacob Mellor,技術長 @ Team Iron
首席技術長

Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。

Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。