本文将介绍如何使用Spire.Presentation for .NET在PowerPoint文档中使用正则表达式替换文本。
C#
using Spire.Presentation;
using System.Text.RegularExpressions;
namespace ReplaceTextWithRegex
{
class Program
{
static void Main(string[] args)
{
//创建Presentation实例
Presentation ppt = new Presentation();
//加载示例文档
ppt.LoadFromFile("Sample.pptx");
//获取第一张幻灯片
ISlide slide = ppt.Slides[0];
//替换该幻灯片中所有“ABC”以及其后到行尾的内容为“ABC def”
Regex regex = new Regex("ABC.*");
string newvalue = "ABC def";
foreach (IShape shape in slide.Shapes)
{
shape.ReplaceTextWithRegex(regex, newvalue);
}
//保存结果文档
ppt.SaveToFile("ReplaceTextWithRegex.pptx", FileFormat.Pptx2013);
}
}
}
VB.NET
Imports Spire.Presentation
Imports System.Text.RegularExpressions
Namespace ReplaceTextWithRegex
Friend Class Program
Private Shared Sub Main(ByVal args As String())
'创建Presentation实例
Dim ppt As Presentation = New Presentation()
'加载示例文档
ppt.LoadFromFile("Sample.pptx")
'获取第一张幻灯片
Dim slide As ISlide = ppt.Slides(0)
'替换该幻灯片中所有“ABC”以及其后到行尾的内容为“ABC def”
Dim regex As Regex = New Regex("ABC.*")
Dim newvalue As String = "ABC def"
For Each shape As IShape In slide.Shapes
shape.ReplaceTextWithRegex(regex, newvalue)
Next
'保存结果文档
ppt.SaveToFile("ReplaceTextWithRegex.pptx", FileFormat.Pptx2013)
End Sub
End Class
End Namespace
原PowerPoint文档:
结果文档: