How to Populate PowerPoint with values in C#

By FoxLearn 7/18/2024 7:54:03 AM   2.45K
To populate a PowerPoint presentation with values in C# Windows Forms using the PptxTemplater library, you can follow these general steps.

How to populate powerpoint with values in C#

Prepare a PowerPoint presentation template (.pptx) with placeholders for dynamic content. These placeholders can be text boxes, tables, shapes, etc., that you'll replace with your data programmatically.

powerpoint template

Drag and drop the Label, TextBox, Button controls from your Visual Studio toolbox on to your form designer, then create a simple form allows you to enter data, then populate data to the powerpoint template file.

c# powerpoint

You need to download PptxTemplater from github website, then copy the PptxTemplater folder you downloaded into your project.

Alternatively, you can install the PptxTemplater library via NuGet Package Manager in your C# project.

Adding a click event handler to the FillData button allows you to fill data from textbox to powerpoint file.

private void btnFillData_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "PowerPoint |*.pptx" })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            // Load the PowerPoint template
            FileInfo fileInfo = new FileInfo(ofd.FileName);
            string fileName = $"{fileInfo.Directory}\\{fileInfo.Name.Replace(fileInfo.Extension, "")}_data{fileInfo.Extension}";
            File.Copy(ofd.FileName, fileName);
            Pptx pptx = new Pptx(fileName, FileAccess.ReadWrite);
            int totalSlide = pptx.SlidesCount();
            if (totalSlide > 0)
            {
                // Replace placeholders with actual data
                PptxSlide slide = pptx.GetSlide(0);//default slide 0
                slide.ReplaceTag("{{fullname}}", txtFullName.Text, PptxSlide.ReplacementType.Global);
                slide.ReplaceTag("{{email}}", txtEmail.Text, PptxSlide.ReplacementType.Global);
                slide.ReplaceTag("{{address}}", txtAddress.Text, PptxSlide.ReplacementType.Global);
                pptx.Close();
                Process.Start(fileName);
            }
        }
    }
}

We will load the PowerPoint template file into your C# application using the PptxTemplater library, then replace the placeholders in the loaded template with your actual data. Finally, Save the PowerPoint with the populated data to a new file.

Related