EXCEL TOOLS

How to Use Create PowerPoint from a Template in C#

Published March 26, 2024
Share:

Introduction

PowerPoint presentations continue to be a standard for efficiently communicating information in commercial, educational, and other domains. PowerPoint is a flexible tool that may improve your communication efforts, whether you're teaching a class, giving project updates to your team, or making a presentation to possible investors. However creating presentations from scratch might take a lot of time, and the efficiency and uniformity of the design may not always be what is wanted. This is where PowerPoint templates come in handy, providing ready-made slides with themes and layouts that can be altered to fit your requirements.

In this post, we'll look at how to use C# to create a PowerPoint from a template. We can expedite the procedure and enable customers to create polished presentations with ease by utilizing the Microsoft PowerPoint Interop library.

How to Use Create PowerPoint from a Template in C#

  1. Create a new C# project.
  2. Launch the PowerPoint program in a new instance.
  3. Insert slides from a template into a newly created presentation.
  4. Create a new file and save the presentation.
  5. Close the PowerPoint program and end the presentation.

Understanding of PowerPoint from template

Let's first review the basic ideas behind writing PowerPoint presentations programmatically before getting into the code. With the PowerPoint Interop library from Microsoft, developers may use .NET languages like C# to communicate with PowerPoint applications. Many functions, including the ability to create slides, add text, insert pictures, and apply formatting, are exposed by this package.

Create a New Visual Studio Project

To start a new Visual Studio project, follow the instructions below.

Launch the Visual Studio application. Before using Visual Studio, make sure you have installed it on your computer.

Select File, then New, and lastly Project.

How to Use Create PowerPoint from a Template in C#: Figure 1 - Create a New Project in Visual Studio. Choose the C# Language and a Console App or Console App (.NET Core) project.

Choose your preferred programming language (C#, for example) from the left side of the "Create a new project" box. Next, from the list of project templates that are available, choose the "Console App" or "Console App (.NET Core)" template. To give your project a name, please fill out the "Name" field.

How to Use Create PowerPoint from a Template in C#: Figure 2 - Configure the Console App project: Add a Project name and Location.

Decide where the project will be stored. To begin working on a new Console application project, click "Next". Then select the appropriate .NET Framework and click on "Create".

How to Use Create PowerPoint from a Template in C#: Figure 3 - Select the appropriate .NET Framework and click on "Create".

In a freshly established C# project, add a reference to the Microsoft PowerPoint Interop library. It is now easier to develop and interact with presentations thanks to this library, which enables communication between your C# code and the PowerPoint application.

Create PowerPoint from Template using C#

Loading the PowerPoint template that forms the basis of our new presentation is the first step. Predefined slide layouts, themes, and content placeholders are frequently seen in templates. The Microsoft.Office.PowerPoint.Interop library's function allows us to open the template file and retrieve its contents from within our C# source code.

using PowerPoint = Microsoft.Office.Interop.PowerPoint;
class Program
{
    static void Main(string [] args)
    {
        // Initialize PowerPoint application
        PowerPoint.Application powerpointApp = new PowerPoint.Application();
        // Load a PowerPoint file
        PowerPoint.Presentation presentation = powerpointApp.Presentations.Open(
            @"C:\Path\To\Existing\output.pptx",
            MsoTriState.msoFalse,
            MsoTriState.msoFalse,
            MsoTriState.msoTrue);
        // ppt slide from a template file
        presentation.Slides.InsertFromFile(
            @"C:\Path\To\External\demo.pptx",
            presentation.Slides.Count + 1,
            1,
            0);
        // Save the updated presentation
        presentation.Save();
        // Close the presentation and quit PowerPoint application
        presentation.Close();
        powerpointApp.Quit();
    }
}
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
class Program
{
    static void Main(string [] args)
    {
        // Initialize PowerPoint application
        PowerPoint.Application powerpointApp = new PowerPoint.Application();
        // Load a PowerPoint file
        PowerPoint.Presentation presentation = powerpointApp.Presentations.Open(
            @"C:\Path\To\Existing\output.pptx",
            MsoTriState.msoFalse,
            MsoTriState.msoFalse,
            MsoTriState.msoTrue);
        // ppt slide from a template file
        presentation.Slides.InsertFromFile(
            @"C:\Path\To\External\demo.pptx",
            presentation.Slides.Count + 1,
            1,
            0);
        // Save the updated presentation
        presentation.Save();
        // Close the presentation and quit PowerPoint application
        presentation.Close();
        powerpointApp.Quit();
    }
}
Imports PowerPoint = Microsoft.Office.Interop.PowerPoint
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Initialize PowerPoint application
		Dim powerpointApp As New PowerPoint.Application()
		' Load a PowerPoint file
		Dim presentation As PowerPoint.Presentation = powerpointApp.Presentations.Open("C:\Path\To\Existing\output.pptx", MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoTrue)
		' ppt slide from a template file
		presentation.Slides.InsertFromFile("C:\Path\To\External\demo.pptx", presentation.Slides.Count + 1, 1, 0)
		' Save the updated presentation
		presentation.Save()
		' Close the presentation and quit PowerPoint application
		presentation.Close()
		powerpointApp.Quit()
	End Sub
End Class
VB   C#

After loading the template, we build a new presentation using its layout. We make use of the PowerPoint presentation file (output.pptx). Which helps us to create a PowerPoint presentation object that will act as a canvas for our material. The template's layout and theme will be carried over into this presentation, giving it a unified visual style.

How to Use Create PowerPoint from a Template in C#: Figure 4 - Second PowerPoint file (demo.pptx) containing the slides you wish to include in your presentation

The presentation.Slides.InsertFromFile() method takes four parameters, namely FileName, Index, SlideStart, SlideEnd.

The path to the PowerPoint file containing the slides you wish to include in your presentation is specified as the first parameter (demo.pptx). The next parameter is the number of slides the user needs to copy to the new file from the template. The other two parameters are optional. These parameters allow us to pass the start and end slide indexes. If we need to extract slides in between two slides we can use these parameters.

You may use a presentation.Save() method to save the presentation after the slides have been inserted using InsertFromFile() method, close the PowerPoint program using the Close() method, and then exit the presentation with the Quit() method. This way, you can improve the content and flexibility of your PowerPoint presentation by dynamically adding slides from external files by utilizing the InsertFromFile technique.

Output

How to Use Create PowerPoint from a Template in C#: Figure 5 - Output: output.pptx

IronXL

Introducing a feature-rich C# library for working with Excel files called IronXL. Iron Software's IronXL provides a wide range of tools for dynamically creating, populating, and formatting Excel documents. With its user-friendly API and extensive documentation, IronXL streamlines Excel interactions in C# and provides developers with a seamless experience for Excel-related tasks.

Features of IronXL

  • Extensive Excel Support: IronXL is capable of opening and manipulating a large number of Excel files in various Excel formats, such as CSV, XLS, and XLSX file formats. Developers can effectively extract data from an existing Excel file utilizing both old and contemporary Excel files thanks to IronXL's robust parsing features.
  • High speed: IronXL prioritizes performance optimization. Excel interactions are reliable and quick because of the use of efficient algorithms and memory management strategies. IronXL provides reduced memory overhead and optimized processing rates, so developers can easily manage huge Excel files.
  • Straightforward and user-friendly API: IronXL's user-friendly API makes it suitable for developers of all skill levels. IronXL reduces the learning curve for C# developers and expedites the process of creating and reading an existing file by providing simple ways to read Excel files, access Excel workbooks, and get data from cells.

To know more about IronXL documentation refer here.

Install IronXL

Io install IronXL, use the instructions and command given in the following steps:

In Visual Studio, navigate to Tools -> NuGet Package Manager -> Package Manager interface.

Enter the following code in the package manager's console tab:

Install-Package IronXL.Excel

The IronXL package is now usable after being downloaded and installed on the current project.

Create Excel Using IronXL

Let's now examine an actual code sample that demonstrates how to write data to an Excel document in C# using IronXL. We'll walk through how to launch a fresh Excel workbook, complete a worksheet, and then save the information to a file:

using IronXL;
class Program
{
    static void Main(string [] args)
    {
            // Create a new WorkBook object
            WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
            // Add a new WorkSheet to the workbook
            WorkSheet workSheet = workBook.CreateWorkSheet("Sheet1");
            // Define sample data
            string [,] data = {
            { "Name", "Age", "City" },
            { "Superman ", "35", "Metropolis" },
            { "Batman", "34", "Metropolis" },
            { "Flash", "30", "Central City" }
        };
            // Populate the worksheet with data
            for (int row = 0; row < data.GetLength(0); row++)
            {
                for (int col = 0; col < data.GetLength(1); col++)
                {
                    workSheet.SetCellValue(row, col, data [row, col]);
                }
            }
            // Save the workbook to a  xlsx file
            workBook.SaveAs("Demo.xlsx");
            // Close the workbook
            workBook.Close();
    }
}
using IronXL;
class Program
{
    static void Main(string [] args)
    {
            // Create a new WorkBook object
            WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
            // Add a new WorkSheet to the workbook
            WorkSheet workSheet = workBook.CreateWorkSheet("Sheet1");
            // Define sample data
            string [,] data = {
            { "Name", "Age", "City" },
            { "Superman ", "35", "Metropolis" },
            { "Batman", "34", "Metropolis" },
            { "Flash", "30", "Central City" }
        };
            // Populate the worksheet with data
            for (int row = 0; row < data.GetLength(0); row++)
            {
                for (int col = 0; col < data.GetLength(1); col++)
                {
                    workSheet.SetCellValue(row, col, data [row, col]);
                }
            }
            // Save the workbook to a  xlsx file
            workBook.SaveAs("Demo.xlsx");
            // Close the workbook
            workBook.Close();
    }
}
Imports IronXL
Friend Class Program
	Shared Sub Main(ByVal args() As String)
			' Create a new WorkBook object
			Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
			' Add a new WorkSheet to the workbook
			Dim workSheet As WorkSheet = workBook.CreateWorkSheet("Sheet1")
			' Define sample data
			Dim data(,) As String = {
				{ "Name", "Age", "City" },
				{ "Superman ", "35", "Metropolis" },
				{ "Batman", "34", "Metropolis" },
				{ "Flash", "30", "Central City" }
			}
			' Populate the worksheet with data
			For row As Integer = 0 To data.GetLength(0) - 1
				For col As Integer = 0 To data.GetLength(1) - 1
					workSheet.SetCellValue(row, col, data (row, col))
				Next col
			Next row
			' Save the workbook to a  xlsx file
			workBook.SaveAs("Demo.xlsx")
			' Close the workbook
			workBook.Close()
	End Sub
End Class
VB   C#

In this code sample, we first create a new WorkBook object using IronXL's Create() function, specifying the necessary Excel file format. The next step is to make a new worksheet within the workbook and explain some sample data in a two-dimensional array. Next, in order to populate the spreadsheet with the sample data, we utilize nested loops to access and set the values of different cells. In order to free up system resources, we shut down the workbook after using the SaveAs() method to save it to a file named "SampleData.xlsx". Similarly, we are able to generate more than one sheet for the target file.

The Excel file created as an output is shown below. To know more about writing Excel files refer to the code examples page.

How to Use Create PowerPoint from a Template in C#: Figure 6 - Excel file output

Conclusion

In conclusion, utilizing C# to create PowerPoint presentations from templates enables users to improve design consistency, expedite workflow, and produce content that has an effect. Developers may save time and work while guaranteeing professional outcomes by automating the creation process and utilizing the features of the Microsoft PowerPoint Interop library. Learning this approach will help you as a presenter, business professional, or educator improve your presenting skills and capture your audience with eye-catching slides.

For C# developers, IronXL is a powerful alternative to Microsoft Excel, providing full support for Excel, great performance, and seamless interaction with the .NET framework. IronXL's user-friendly API and fine-grained control over Excel documents simplify Excel writing in C#. This facilitates the process for developers to automate Excel-related tasks, export data, and generate dynamic reports. Whether they are creating Excel files for desktop, web, or mobile apps, C# developers can count on IronXL to streamline Excel-related tasks and unleash the full potential of Excel in their C# programs.

IronXL costs $749 when it first launches. In addition, users have the option to pay a membership fee of one year to obtain product assistance and updates. For a fee, IronXL offers protection against unrestrained redistribution. To find out more about the approximate cost, please visit this license page. View more about Iron Software by clicking this website link.

< PREVIOUS
How to View Powerpoint Files in C#
NEXT >
Test Your Regex Patterns with .NET Regex Tester

Ready to get started? Version: 2024.11 just released

Free NuGet Download Total downloads: 1,111,773 View Licenses >