エクセルツール

C# で PowerPoint ファイルを表示する方法

イントロダクション

ソフトウェア開発の分野において、豊かで魅力的なユーザーエクスペリエンスを提供するためには、多くのメディア種類をプログラムに組み込む能力が必要です。 Microsoft Office PowerPointのプレゼンテーションは情報を伝達するために頻繁に使用されるため、C# WinFormsプログラムにPowerPointビューアコントロールを組み込むことは有利です。 この記事では、そのような種類の制御を統合し、開発者がアプリにPowerPoint閲覧機能を追加して改良する方法について説明します。 この記事では、MS PowerPoint ViewerをインストールせずにC# PowerPoint Viewerを作成します。

C#でPowerPointファイルを表示する方法

  1. PowerPointアプリケーションインスタンスを作成します。

  2. プロジェクトにInterop参照を追加する

  3. インスタンスを使用してプレゼンテーションを開く。

  4. エクスポートファイルの出力フォルダーを確認して作成します。

  5. スライド画像をPictureボックスに読み込む。 ボタンを使用してスライドを移動します。

  6. プレゼンテーションを閉じてアプリケーションを終了します。

パワーポイントビューアコントロールを理解する

PowerPointプレゼンテーションは、教育やビジネスを含むさまざまな分野で広く使用されています。 WinFormsアプリケーションにPowerPointビューアーコントロールを組み込むことにはいくつかの利点があります。

  • スムーズな統合: ユーザーがアプリケーション内で直接PowerPointプレゼンテーションを表示および操作できるようにすることで、ユーザーはさまざまなプログラムを切り替える時間を短縮し、ワークフローを合理化できます。
  • ユーザーエクスペリエンスの向上: プログラムは、PowerPointスライドを操作するための認識しやすいインターフェースを提供することで、ユーザーエクスペリエンスと効率を向上させます。
  • 強化された柔軟性: .NETアプリケーションのWindows開発者向けには、ナビゲーションコントロールを追加したり、表示モードを導入することで、開発者がビューワーコントロールをユニークなニーズに合わせてカスタマイズできます。

参照の追加

まず、必要なアセンブリへの参照を追加します: プロジェクトにMicrosoft.Office.Interop.PowerPointの参照を追加するには、Visual Studioでプロジェクトを右クリックし、「追加」>「参照」を選択して、COMタブからそれらを追加します。

パワーポイントビューアー

Microsoft.Office.Interop.PowerPoint 名前空間は、プログラムで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内でのPowerPointとのやり取りに含まれています。 PowerPointViewerApp 名前空間内で、PowerPointViewer という WinForms フォームクラスを定義します。 ビューPPTアプリケーションの主なユーザーインターフェイスは、このフォームになります。

PowerPointアプリケーションおよびプレゼンテーションへの参照が、プライベートフィールドpptApplicationpptPresentationに保存されることが発表されました。 コンストラクターは、InitializeComponent() を使用することにより、デザイナーによって定義されたフォームのビジュアルコンポーネントを設定し、フォームを初期化します。 フォームが読み込まれると、InitializeComponent() 関数が呼び出されます。 PowerPointアプリケーション(pptApplication)はこの時点で初期化され、アクセス可能になります。

次に、pptFilePathで指定されたPowerPointファイルを起動します。 pptApplication.Presentations を使用して、Open() 関数にパス (pptFilePath) を提供することで PowerPoint ファイルを開きます。 手続きによって開かれたプレゼンテーションを表すPresentationオブジェクトが返されます。

PowerPointプレゼンテーションの最初のスライドを表示するには、DisplaySlide() 関数を使用します。 最初のスライドのインデックスは1です。PictureBoxコントロールに表示されるスライドは、この関数の結果です。 選択されたスライドをPNGファイルとしてエクスポートするためにExport()関数を使用します。エクスポートされたPNGファイルは、システムの一時フォルダに一時的に保存されます。 ImageLocation() メソッドを使用して、エクスポートされたPNGファイルをPictureBoxコントロールに読み込みます。 これらの技術はスライドの切り替えを処理します。

ナビゲーションボタンbtnPrevious_ClickbtnNext_Clickは、それぞれ前のスライドと次のスライドに移動します。 pptPresentationを使用して、slideIndex変数でスライドのインデックスを取得できます。 現在のスライドインデックスが1からスライドの全数までの有効範囲内にある場合、DisplaySlide()を前のスライドまたは次のスライドのインデックスを使ってそれぞれ呼び出します。

フォームが閉じられると、Close() 関数が呼び出されます。 ここでは、PowerPointプログラムを終了し、Quit()メソッドを使用してPowerPointアプリケーションを終了することにより、システムリソースを解放してリソース管理を正しく行うことを保証します。

PowerPointファイル

C# で PowerPoint ファイルを表示する方法: 図 1 - PowerPoint ファイル demo.pptx

出力: PowerPoint Viewer

C#でPowerPointファイルを表示する方法: 図2 - PowerPointViewer.cs

IronXL

C#でのExcelファイル操作は、人気の.NET ExcelライブラリIronXLを使用することで簡単になります。 その広範な機能セットにより、Excelファイルの読み取り、生成、修正に対応できる多用途ツールです。

以下に、IronXLの主要な属性について説明します:

簡単なアクセスと高速

  • IronXLを使用すると、開発者は現在のExcelファイルからデータを読み取り、新しいまたは既存のExcelファイルに迅速にデータを書き込むことができます。 これは、セル値、数式、フォーマットなどのワークブックおよびワークシートプロパティへのアクセスに関するものです。

充実したExcelサポート

  • 開発者はIronXLを使用して、データベースやCSVファイルなどのソースからExcelスプレッドシートにデータをインポートすることができます。 同様に、Excelファイルからのデータは、CSV、HTML、XML、PDFなどの多様なフォーマットにエクスポートすることができます。

柔軟性

  • IronXLを使用すると、開発者はExcelファイルからワークシートを動的に追加、変更、および削除することができます。 これは、アプリケーションの要件に応じてデータ形式と構成の柔軟性を提供します。

正確な変更

  • IronXLのおかげで、Excelスプレッドシートの個々のセルを正確に修正できます。 開発者はセルの値、数式、スタイル、フォーマット、および他の機能をプログラムで設定できます。

    ドキュメントの詳細についてはこちらを参照してください。

IronXLをインストール

続行する前に、まず IronXL をNuGetパッケージマネージャーコンソールを使用してインストールしましょう。

Install-Package IronXL.Excel
Install-Package IronXL.Excel
SHELL

IronXLはインストール後に私たちのC#プロジェクトで利用することができます。

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 ライブラリによって提供されるクラスとメソッドが含まれています。 読み取りたい Excel ファイルである sample.xlsx のパスが指定されています。 WorkBookを利用して、Excelファイルが読み込まれます。 Load() メソッドによって提供される Workbook オブジェクトは、Excel ワークブックを表します。 ワークブックの最初のワークシートには、workbook.WorkSheets[0]を使用してアクセスできます。 ワークシートの行と列をネストされたfor each ループを使用して繰り返します。 各セルの値をコンソールに送信します。

C#でPowerpointファイルを表示する方法: 図3 - IronXL出力結果

IronXLのコード例について詳しく知るには、こちらを参照してください。

結論

いくつかのソフトウェアアプリケーションは、C#を使用してPowerPointプレゼンテーションを画像に変換する必要があります。 プロセスはMicrosoft.Office.Interop.PowerPoint名前空間が使用されるかどうかにかかわらず、比較的迅速に完了する可能性があります。 この記事のコードサンプルを使えば、C#プログラムにPowerPointから画像への変換機能を簡単に組み込むことができ、情報の変更や配信のための多くの可能性が広がります。

IronXL は、Excelをターゲットシステムにインストールしたり、Interopライブラリに依存することなく、C#でExcel操作を簡単かつ効率的に行う方法を提供します。 その包括的な機能セットとユーザーフレンドリーなAPIにより、IronXLはC#アプリケーションでExcelデータを扱う開発者にとって便利なツールです。 それは、Excelファイルの読み取り、書き込み、編集などのタスクを簡素化します。 Excel関連の開発プロジェクトでは、IronXLはデータの処理、レポートの作成、またはスプレッドシートの自動化のいずれの場合でも、生産性と柔軟性を向上させる安定したソリューションを提供します。

IronXLは、非商用利用に制限のある無料のコミュニティエディションを提供しました。 有料版は$749から始まり、サブスクリプションまたは永続ライセンススキームを通じて取得できます。 それらはより完全に機能し、より多くの機能やサポートを提供します。 IronXLは無料トライアルライセンスも提供しています。 ライセンスに関する包括的で最新の情報については、ライセンスページをご覧ください。 こちらのウェブサイトを訪れて、Iron Software製品について詳しく学んでください。

リーガン・パン
ソフトウェアエンジニア
レーガンはリーディング大学で電子工学の学士号を取得しました。Iron Softwareに入社する前の仕事では、一つのタスクに集中して取り組んでいました。Iron Softwareでは、営業、技術サポート、製品開発、マーケティングのいずれにおいても広範な業務に携わることが最も楽しいと感じています。彼は、Iron Softwareライブラリを開発者がどのように使用しているかを理解し、その知識を使ってドキュメントを継続的に改善し、製品を開発することを楽しんでいます。
次へ >
C#でテンプレートからPowerPointを作成する方法