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—


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM