跳過到頁腳內容
PPT 工具
如何使用C#創建PowerPoint演示文稿

如何使用 C# 程式化創建和自動化 PowerPoint 演示文稿

手動製作同樣的 PowerPoint 簡報是一項乏味且容易出錯的工作,沒有任何開發人員會喜歡這樣的工作。 無論是產生每週的銷售報告、每月的財務摘要,或是個人化的客戶提案,都是成熟的自動化流程。 多年來,.NET 世界中最常用的解決方案是 Microsoft Office Interop,這是一種允許對 Office 應用程式進行程式化控制的技術。 然而,這種方法也有很大的缺點:它需要在伺服器上安裝 Microsoft Office 的授權版本,在伺服器環境中不穩定是出了名的,而且它完全排除了在 Linux、macOS 或 Docker 容器上進行現代化、跨平台部署的可能性。

幸運的是,有一個更好的方法。 本教學將教您如何使用IronPPT for.NET以 C# 程式化的方式建立 PowerPoint 簡報,IronPPT for.NET 是專為現代開發而打造的強大且輕量的函式庫。 我們將探討如何自動化從建立簡單的投影片到從範本中產生複雜、資料驅動的簡報,以及完整的表格和圖表。 有了 IronPPT,您可以建立快速、可擴充且可靠的簡報自動化工作流程,這些流程可在任何地方執行,而不需依賴 Microsoft Office。

IronPPT - C# 簡報函式庫。 _TheIronPPT for.NETlibrary allows developers to programmatically create and manage PowerPoint files in C#._TheIronPPT for.NETlibrary 允許開發人員使用 C# 程式化地建立和管理 PowerPoint 檔案。

如何開始在 C# 中產生 PowerPoint? C# 的 PowerPoint 自動化入門非常簡單直接。IronPPT for.NET以 NuGet 套件的形式發佈,可在幾秒鐘內直接安裝到您的 Visual Studio 專案中。

步驟 1:安裝 IronPPT 函式庫

`NuGet Package Manager` > `Package Manager Console`) 並輸入下列指令: ```shell :ProductInstall ``` 另外,您也可以在 NuGet Package Manager GUI 中搜尋「IronPPT」,並從那裡進行安裝。 ![ 透過 NuGet 套件管理程式畫面安裝 IronPPT](/static-assets/pdf/blog/csharp-create-powerpoint-tutorial/csharp-create-powerpoint-tutorial-2.webp) _Visual Studio 中的 NuGet 套件管理員,顯示 IronPPT 函式庫的安裝。

步驟 2:建立並儲存您的第一份簡報

如何以程式化的方式新增和操作幻燈片? 簡報是幻燈片的集合。 IronPPT 提供了簡單直觀的 API 來管理這些幻燈片,讓您可以 [根據應用程式的需要來新增、載入和重複使用這些幻燈片](/csharp/ppt/examples/add-slide/)。

載入現有簡報並新增幻燈片

Two Blank Slides 相同的簡報,現在透過 C# 程式碼增加了第二張空白的幻燈片。 ```csharp 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"); ```

複製幻燈片以達到一致的佈局

在幻燈片中加入豐富內容的最佳方式是什麼? 有了幻燈片之後,下一步就是將有意義的內容填充其中。 IronPPT 提供豐富的物件模型,可用於新增和格式化文字、插入影像以及繪製圖形。 ### 使用文字、字型和段落。 文字是任何簡報中最常見的元素。 在 IronPPT 中,文字是透過物件的層級架構來管理的:`Shape`(作為文字方塊)、`Paragraph` 和 `Text`。 此結構可提供定位與樣式的細部控制。 讓我們在兩張幻燈片的簡報上進行擴充,在第一張幻燈片上加入樣式化標題,並在第二張幻燈片上加入項目清單。 ```csharp 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"); ``` 本範例展示了幾個關鍵概念: - **Shapes as Textboxes**:我們建立一個類型為 `Rectangle` 的 `Shape` 以作為文字的容器。 這讓我們可以精確控制其位置和大小。 - **段落**:透過 `Paragraph` 物件新增文字內容。 - **樣式**:`Paragraph`的 `DefaultTextStyle` 屬性允許流暢的字型、大小、顏色和重量樣式。 `Style` 屬性可控制段落層級的格式,例如對齊方式和小點。 !a href="/static-assets/pdf/blog/csharp-create-powerpoint-tutorial/csharp-create-powerpoint-tutorial-5.webp"> 加入文字和文字方塊。 _第一張幻燈片現在有一個樣式化的標題,而第二張幻燈片則包含一個項目列表。

插入和定位圖片

繪製和自訂圖形如何製作資料驅動的簡報? PowerPoint 自動化的真正威力在於從動態資料來源產生簡報。 這正是 IronPPT 的優勢所在,它能讓您建立複雜的報表系統,可以快速建立表格、圖表和填充範本。 此功能使其有別於基本的函式庫,並將其定位為 Aspose 和 Syncfusion 等工具的有力競爭者,這些工具也強調資料驅動的功能。

使用動態報表的範本

步驟 1:建立 PowerPoint 範本步驟 2:在 C# 中填充範本; { { "{{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"); ``` 這種以模板為基礎的方法非常強大。 它將設計與資料分離,允許設計人員在 PowerPoint 中修改範本的外觀和感覺,而不需要修改任何程式碼。

從資料集合產生表格

` )以程式化的方式建立和填充表格。 假設我們有一個簡單的 `Product` 類別和一個產品清單。 以下程式碼將會產生一個新的幻燈片,其中包含一個顯示這些資料的表格。 ```csharp // ---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 { 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"); ```

新增圖表以可視化資料

為何選擇專用程式庫而非 Office Interop? 對於考慮以程式化方式製作 PowerPoint 的開發人員而言,通常會選擇使用 Microsoft Office Interop 或 IronPPT 之類的專用第三方函式庫。 雖然 Interop 在擁有 Office 授權的情況下是「免費」的,但它並非針對現代伺服器端應用程式的需求而設計。 下表概述了關鍵差異。 |特點 / 考慮因素|IronPPT for.NET|Microsoft.Office.Interop.PowerPoint| | ---| ---| ---| |伺服器端依賴性需要在伺服器上安裝 Microsoft Office。| |效能與擴充性部署複雜性平台支援Windows、Linux、macOS、Docker、Azure、AWS。|僅限 Windows。 不適合現代跨平台部署。 | |API 設計與易用性穩定性企業 PowerPoint 自動化的最佳實務
立即開始使用 IronPPT。
green arrow pointer
For more detailed information, you can explore the official [IronPPT documentation](/csharp/ppt/docs/) or dive deep into the classes and methods in the [API Reference](/csharp/ppt/object-reference/api/). {i:(Aspose是其各自擁有者的註冊商標。 本網站與 Aspose 無任何關聯、背書或贊助。 所有產品名稱、標誌和品牌均為其各自擁有者的財產。 比較內容僅供參考,並反映撰寫時的公開資訊。)}]

常見問題解答

我怎樣才能在 C# 中自動化 PowerPoint 演示文稿?

您可以使用 IronPPT for .NET 自動化 PowerPoint 演示文稿。這個庫允許您程式化地創建、編輯和操作幻燈片,無需依賴微軟 Office Interop。

.NET 庫與微軟 Office Interop 相比,在 PowerPoint 自動化方面有哪些優勢?

使用像 IronPPT 這樣的 .NET 庫提供了穩定性、跨平台兼容性,並消除了安裝微軟 Office 許可的需求,使其成為伺服器和容器環境的理想選擇。

我怎樣才能使用 C# 向 PowerPoint 演示文稿添加新幻燈片?

使用 IronPPT,您可以在初始化演示文稿後,使用 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, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & IronSuite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。