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 @   E-iceblue  阅读(336)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
点击右上角即可分享
微信分享提示