天天看點

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# 使用正規表達式替換PPT中的文本(附vb.net代碼)
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      

替換效果對比:

C# 使用正規表達式替換PPT中的文本(附vb.net代碼)

—End—