EXCEL 工具

如何在 C# 中查看 PowerPoint 文件

里根普恩
里根普恩
2024年4月3日
分享:

介紹

在軟體開發領域,提供豐富且吸引人的用戶體驗需要將多種媒體類型整合到程式中。 由於 Microsoft Office PowerPoint 簡報經常用於傳達資訊,將 PowerPoint 查看器控制項整合到 C# WinForms 程式中是有利的。 本文介紹如何整合此類控制,讓開發人員能夠在其應用程式中新增 PowerPoint 檢視功能並加以改進。 在本文中,我們將在不安裝MS PowerPoint Viewer的情況下創建C# PowerPoint Viewer。

如何在C#中查看PowerPoint文件

  1. 創建 PowerPoint 應用程式實例。

  2. 將互操作參考添加到專案中

  3. 使用實例打開簡報。

  4. 檢查和建立匯出文件的輸出資料夾。

  5. 將建立的幻燈片圖片載入圖片框中。 使用按鈕在幻燈片之間切換。

  6. 關閉簡報並退出應用程式。

了解 PowerPoint 檢視器控制項

PowerPoint 簡報在各個領域中廣泛使用,包括教育和商業。 將 PowerPoint 檢視器控制項整合到 WinForms 應用程式中有許多優點。

  • 順暢整合:透過允許使用者在應用程式中直接查看和互動 PowerPoint 簡報,使用者可以減少在不同程式間切換的時間,並簡化工作流程。
  • 增強使用者體驗:該程式透過提供可識別的界面來處理PowerPoint幻燈片,提高了使用者體驗和效率。
  • 增強的靈活性:在 Windows 開發人員使用 .NET 應用程式時,透過新增導航控制或引入顯示模式,開發人員可以調整檢視器控制以滿足特定需求。

新增參考

首先添加對必要程序集的引用:要在您的專案中添加Microsoft.Office.Interop.PowerPoint引用,請在 Visual Studio 中右鍵點擊專案,選擇“添加” > “參考”,然後從 COM 標籤中添加它們。

查看器 PowerPoint

Microsoft.Office.Interop.PowerPoint namespace 提供用於以程式方式與 PowerPoint 簡報互動的類別和方法。 確保系統已安裝 PowerPoint。 讓我們剖析並解釋前面的範例中給出的以下代碼:

using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataTableWindowsForm
{
    public partial class PowerPointViewer : Form
    {
        private Microsoft.Office.Interop.PowerPoint.Application pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();
        private Presentation pptPresentation;
        private string outputFolder = @"output_images";
        private int slideIndex = 1;
        public PowerPointViewer()
        {
            InitializeComponent();
        }
        private void DisplaySlide()
        {
            if (!Directory.Exists(outputFolder))
                Directory.CreateDirectory(outputFolder);
            // Export the slide as an png file
            string tempHtmlFile = Path.Combine(outputFolder, "temp.png");
            pptPresentation.Slides [slideIndex].Export(tempHtmlFile, "png", 1024, 768);
            // Load the HTML file into the picture box control
            pictureBox1.ImageLocation = tempHtmlFile;
        }
        private void Next_Click(object sender, EventArgs e)
        {
            int currentSlideIndex = slideIndex;
            if (currentSlideIndex < pptPresentation.Slides.Count)
            {
                slideIndex = slideIndex + 1;
                DisplaySlide();
            }
        }
        private void PowerPointViewercs_Load(object sender, EventArgs e)
        {
            // Load PowerPoint Presentation
            string pptFilePath = "demo.pptx"; // Path to your PowerPoint file
            pptPresentation = pptApplication.Presentations.Open(pptFilePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
        // Load PowerPoint files here
            DisplaySlide();
        }
        private void Previous_Click(object sender, EventArgs e)
        {
            int currentSlideIndex = slideIndex;
            if (currentSlideIndex > 1)
            {
                slideIndex = slideIndex - 1;
                DisplaySlide();
            }
        }
        private void PowerPointViewercs_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Close the PowerPoint presentation and quit the application when the form is closing
            pptPresentation.Close();
            pptApplication.Quit();
        }
    }
}
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataTableWindowsForm
{
    public partial class PowerPointViewer : Form
    {
        private Microsoft.Office.Interop.PowerPoint.Application pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();
        private Presentation pptPresentation;
        private string outputFolder = @"output_images";
        private int slideIndex = 1;
        public PowerPointViewer()
        {
            InitializeComponent();
        }
        private void DisplaySlide()
        {
            if (!Directory.Exists(outputFolder))
                Directory.CreateDirectory(outputFolder);
            // Export the slide as an png file
            string tempHtmlFile = Path.Combine(outputFolder, "temp.png");
            pptPresentation.Slides [slideIndex].Export(tempHtmlFile, "png", 1024, 768);
            // Load the HTML file into the picture box control
            pictureBox1.ImageLocation = tempHtmlFile;
        }
        private void Next_Click(object sender, EventArgs e)
        {
            int currentSlideIndex = slideIndex;
            if (currentSlideIndex < pptPresentation.Slides.Count)
            {
                slideIndex = slideIndex + 1;
                DisplaySlide();
            }
        }
        private void PowerPointViewercs_Load(object sender, EventArgs e)
        {
            // Load PowerPoint Presentation
            string pptFilePath = "demo.pptx"; // Path to your PowerPoint file
            pptPresentation = pptApplication.Presentations.Open(pptFilePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
        // Load PowerPoint files here
            DisplaySlide();
        }
        private void Previous_Click(object sender, EventArgs e)
        {
            int currentSlideIndex = slideIndex;
            if (currentSlideIndex > 1)
            {
                slideIndex = slideIndex - 1;
                DisplaySlide();
            }
        }
        private void PowerPointViewercs_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Close the PowerPoint presentation and quit the application when the form is closing
            pptPresentation.Close();
            pptApplication.Quit();
        }
    }
}
Imports Microsoft.Office.Core
Imports Microsoft.Office.Interop.PowerPoint
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms
Namespace DataTableWindowsForm
	Partial Public Class PowerPointViewer
		Inherits Form

		Private pptApplication As New Microsoft.Office.Interop.PowerPoint.Application()
		Private pptPresentation As Presentation
		Private outputFolder As String = "output_images"
		Private slideIndex As Integer = 1
		Public Sub New()
			InitializeComponent()
		End Sub
		Private Sub DisplaySlide()
			If Not Directory.Exists(outputFolder) Then
				Directory.CreateDirectory(outputFolder)
			End If
			' Export the slide as an png file
			Dim tempHtmlFile As String = Path.Combine(outputFolder, "temp.png")
			pptPresentation.Slides (slideIndex).Export(tempHtmlFile, "png", 1024, 768)
			' Load the HTML file into the picture box control
			pictureBox1.ImageLocation = tempHtmlFile
		End Sub
		Private Sub Next_Click(ByVal sender As Object, ByVal e As EventArgs)
			Dim currentSlideIndex As Integer = slideIndex
			If currentSlideIndex < pptPresentation.Slides.Count Then
				slideIndex = slideIndex + 1
				DisplaySlide()
			End If
		End Sub
		Private Sub PowerPointViewercs_Load(ByVal sender As Object, ByVal e As EventArgs)
			' Load PowerPoint Presentation
			Dim pptFilePath As String = "demo.pptx" ' Path to your PowerPoint file
			pptPresentation = pptApplication.Presentations.Open(pptFilePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse)
		' Load PowerPoint files here
			DisplaySlide()
		End Sub
		Private Sub Previous_Click(ByVal sender As Object, ByVal e As EventArgs)
			Dim currentSlideIndex As Integer = slideIndex
			If currentSlideIndex > 1 Then
				slideIndex = slideIndex - 1
				DisplaySlide()
			End If
		End Sub
		Private Sub PowerPointViewercs_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
			' Close the PowerPoint presentation and quit the application when the form is closing
			pptPresentation.Close()
			pptApplication.Quit()
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

首先,我們匯入所需的命名空間。 檔案操作由 System.IO 處理,System.Windows.Forms 提供 WinForms 功能,而 Microsoft.Office 類用於在 PowerPoint 中進行互動。 在 PowerPointViewerApp 命名空間中,我們定義了一個名為 PowerPointViewer 的 WinForms 表單類別。 檢視 PPT 應用程式的主要使用者介面將是此表單。

已宣布有關 PowerPoint 應用程式和簡報的參考將儲存在兩個私有欄位pptApplicationpptPresentation中。 透過使用InitializeComponent(),建構函式設置由設計師定義的表單視覺元件並初始化該表單。 當表單加載時,會呼叫 InitializeComponent() 函數。 PowerPoint 應用程式(pptApplication)已初始化,並在此時可供使用。

接下來,我們啟動pptFilePath指定的 PowerPoint 文件。 使用pptApplication.Presentations,我們通過將 PowerPoint 文件的路徑 (pptFilePath) 提供給 Open() 函數來打開它。 程序返回一個表示已開啟簡報的演示文稿對象。

要顯示 PowerPoint 簡報的第一張幻燈片,我們使用 DisplaySlide() 函數。 第一張幻燈片的索引是1。顯示在圖片框控件中的幻燈片是此功能的結果。 我們使用Export()函數將選定的幻燈片匯出為PNG檔。匯出的PNG檔暫時存儲在系統的臨時資料夾中。 使用 ImageLocation() 方法,我們將匯出的 PNG 檔載入到 PictureBox 控制項中。 這些技術負責在幻燈片之間切換。

導航按鈕btnPrevious_ClickbtnNext_Click分別帶您前往上一張和下一張幻燈片。 使用pptPresentation,我們可以在slideIndex變數中獲取幻燈片的索引。 如果當前幻燈片的索引在1到所有幻燈片總數之間的有效範圍內,則分別使用上一張或下一張幻燈片的索引來調用DisplaySlide()。

當表單關閉時,Close() 函數被調用。 在這裡,我們透過使用Quit()方法退出 PowerPoint 程序並終止 PowerPoint 應用程式來釋放系統資源,以確保資源管理正確進行。

PowerPoint 檔案

如何在C#中查看PowerPoint文件:圖1 - PowerPoint文件demo.pptx

輸出:PowerPoint 檢視器

如何在 C# 中查看 Powerpoint 文件:圖 2 - PowerPointViwercs

IronXL

使用受歡迎的 .NET Excel Library IronXL,在 C# 中進行 Excel 文件操作變得更容易。 由於具有廣泛的功能集來讀取、生成和修改 Excel 文件,它是一個適合多種應用的多功能工具。

以下,我將介紹一些IronXL的主要特性:

簡易存取和高速

  • 使用 IronXL,開發人員可以從現有的 Excel 文件中讀取數據,並快速將數據寫入新的或現有的 Excel 文件。 這解決了存取工作簿和工作表屬性的方法,例如儲存格的值、公式和格式設定。

廣泛的 Excel 支援

  • 開發人員可以使用 IronXL 將資料庫和 CSV 文件等其他來源的數據導入到 Excel 試算表中。 同樣,Excel 文件中的數據可以匯出為多種格式,包括 CSV、HTML、XML 和 PDF。

靈活性

  • 使用 IronXL,開發者可以動態添加、修改和刪除 Excel 文件中的工作表。 這允許根據應用程式的需求在資料格式和組織上具有彈性。

精確的修改

  • 由於 IronXL,Excel 試算表中的個別儲存格可以被準確地修改。 開發人員可以通過程式設定儲存格值、公式、樣式、格式和其他功能。

    如需了解更多文件資訊,請參閱這裡

安裝 IronXL

在繼續之前,我們先使用 NuGet Package Manager Console 安裝IronXL

Install-Package IronXL.Excel

在安裝後,您可以在我們的 C# 項目中使用 IronXL。

使用IronXL進行Excel操作

讓我們看看一個假設的情境,我們想使用IronXL從Excel文件中讀取數據。 以下是一個實現此功能的小範例:

using IronXL;
using System;
class Program
{
    static void Main(string [] args)
    {
        // Path to the Excel file
        string excelFilePath = "sample.xlsx";
        // Load the Excel file
        WorkBook workbook = WorkBook.Load(excelFilePath);
        // Access the first worksheet
        WorkSheet worksheet = workbook.WorkSheets [0];
        // Iterate through rows and columns to read data
        foreach (var row in worksheet.Rows)
        {
            foreach (var cell in row)
            {
                Console.Write(cell.Value + "\t");
            }
            Console.WriteLine();
        }
    }
}
using IronXL;
using System;
class Program
{
    static void Main(string [] args)
    {
        // Path to the Excel file
        string excelFilePath = "sample.xlsx";
        // Load the Excel file
        WorkBook workbook = WorkBook.Load(excelFilePath);
        // Access the first worksheet
        WorkSheet worksheet = workbook.WorkSheets [0];
        // Iterate through rows and columns to read data
        foreach (var row in worksheet.Rows)
        {
            foreach (var cell in row)
            {
                Console.Write(cell.Value + "\t");
            }
            Console.WriteLine();
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronXL
Imports System
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Path to the Excel file
		Dim excelFilePath As String = "sample.xlsx"
		' Load the Excel file
		Dim workbook As WorkBook = WorkBook.Load(excelFilePath)
		' Access the first worksheet
		Dim worksheet As WorkSheet = workbook.WorkSheets (0)
		' Iterate through rows and columns to read data
		For Each row In worksheet.Rows
			For Each cell In row
				Console.Write(cell.Value & vbTab)
			Next cell
			Console.WriteLine()
		Next row
	End Sub
End Class
$vbLabelText   $csharpLabel

我們首先添加必要的命名空間。 IronXL 命名空間包含由 IronXL 函式庫提供的類別和方法。 給定sample.xlsx檔案的路徑是我們想要讀取的Excel文件。 利用WorkBook載入Excel文件。 Workbook 物件由 Load() 方法提供,代表 Excel 工作簿。 我們可以使用 workbook.WorkSheets [0] 訪問工作簿的第一個 工作表。 我們使用堆疊的 for each 迴圈來遍歷工作表的行和列。 我們將每個單元格的值發送到控制台。

如何在 C# 中查看 Powerpoint 文件:圖 3 - IronXL 輸出

欲了解更多 IronXL 程式碼範例,請參考這裡

結論

多個軟體應用需要使用 C# 將 PowerPoint 簡報轉換為圖片。 無論是否使用 Microsoft.Office.Interop.PowerPoint 命名空間,此過程可能很快就會完成。 您可以輕鬆地將 PowerPoint 轉換為圖像整合到您的 C# 程式中,這篇文章的代碼範例可以幫助您,在資訊變更和傳遞方面開啟一個全新的可能性世界。

IronXL 提供了一種簡單且有效的方法來在 C# 中進行 Excel 操作,無需在目標系統上安裝 Excel 或依賴 Interop 庫。 IronXL 擁有全面的功能集和使用者友好的 API,是開發人員在 C# 應用程式中處理 Excel 數據的實用工具。 它簡化了讀取、寫入和編輯 Excel 文件的任務。 對於與 Excel 相關的開發專案,IronXL 提供了一個穩定的解決方案,可以提高生產力和靈活性,無論您是在處理數據、製作報告,還是自動化試算表任務。

IronXL 提供了一個免費的社群版,僅限於非商業用途。 付費版本起價為$749,可以通過訂閱或永久授權方案獲得。 它們功能更全面,提供更多功能和支援。 IronXL 也提供免費試用許可。 如需有關許可的全面和最新資訊,請造訪許可頁面。 訪問這個網站以了解更多有關Iron Software產品的信息。

里根普恩
軟體工程師
Regan 畢業於雷丁大學,擁有電子工程學士學位。在加入 Iron Software 之前,他的工作角色讓他專注於單一任務;而他在 Iron Software 工作中最喜歡的是他所能承擔的工作範圍,無論是增加銷售價值、技術支持、產品開發或市場營銷。他喜歡了解開發人員如何使用 Iron Software 庫,並利用這些知識不斷改進文檔和開發產品。
下一個 >
如何在 C# 中使用模板創建 PowerPoint