C# 使用正则表达式替换PPT中的文本(附vb.net代码)

文本介绍如何在C#程序中使用正则表达式替换PPT幻灯片中的指定文本内容。具体操作步骤如下:

1. 在程序中引用Spire.Presentation.dll。两种方法可参考如下:

  (1)直接在程序中通过nuget搜索 “ Spire.Presentation ” 下载安装。

  (2)将 Spire.Presentation for .NET 6.8.3 包下载到本地,解压,手动将Bin文件夹路径下的Spire.Presentation.dll添加引用至程序。

两种方法均可添加该程序集文件。添加结果如图:

 

 

C#

using Spire.Presentation;
using System.Text.RegularExpressions;

namespace ReplaceText_PPT
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建Presentation实例
            Presentation ppt = new Presentation();
            //加载示例文档
            ppt.LoadFromFile("test.pptx");

            //获取第1张幻灯片
            ISlide slide = ppt.Slides[0];

            //替换该幻灯片中所有“工作”以及其后到行尾的内容为“WORK”
            Regex regex = new Regex("工作.*");
            string newvalue = "WORK";
            foreach (IShape shape in slide.Shapes)
            {
                shape.ReplaceTextWithRegex(regex, newvalue);
            }

            //保存结果文档
            ppt.SaveToFile("ReplaceTextWithRegex.pptx", FileFormat.Pptx2013);
            System.Diagnostics.Process.Start("ReplaceTextWithRegex.pptx");
        }
    }
}

Vb.net

Imports Spire.Presentation
Imports System.Text.RegularExpressions

Namespace ReplaceText_PPT
    Class Program
        Private Shared Sub Main(args As String())
            '创建Presentation实例
            Dim ppt As New Presentation()
            '加载示例文档
            ppt.LoadFromFile("test.pptx")

            '获取第1张幻灯片
            Dim slide As ISlide = ppt.Slides(0)

            '替换该幻灯片中所有“工作”以及其后到行尾的内容为“WORK”
            Dim regex As New Regex("工作.*")
            Dim newvalue As String = "WORK"
            For Each shape As IShape In slide.Shapes
                shape.ReplaceTextWithRegex(regex, newvalue)
            Next

            '保存结果文档
            ppt.SaveToFile("ReplaceTextWithRegex.pptx", FileFormat.Pptx2013)
            System.Diagnostics.Process.Start("ReplaceTextWithRegex.pptx")
        End Sub
    End Class
End Namespace

替换效果对比:

 

—End—

posted @ 2021-08-30 14:40  E-iceblue  阅读(316)  评论(0编辑  收藏  举报