在C#中以编程方式在PPTX/PPT中查找和替换文本

163 阅读2分钟

查找和替换文本通常用于更新 PowerPoint 演示文稿中的内容。但是,为了对一批演示执行此操作,您需要自动化。因此,本文介绍了如何使用 C# 以编程方式查找和替换 PowerPoint PPTX/PPT 中的文本。

  • 使用 C# 在 PPTX 中查找和替换文本

为了查找和替换 PowerPoint 演示文稿中的文本,我们将使用Aspose.Slides for .NET,它是一个功能丰富的 API,旨在从 .NET 应用程序中创建和操作 PowerPoint 演示文稿。

>>你可以下载Aspose.Slides 最新版测试体验。

使用 C# 在 PowerPoint PPTX 中查找和替换文本

以下是使用 C# 在 PPTX 演示文稿中查找和替换文本的步骤。

  • 使用Presentation类加载 PowerPoint 演示文稿。
  • 循环播放演示文稿中的每张幻灯片。
  • 在每次迭代中,获取ITextFrame数组中的文本框架。
  • 循环遍历 ITextFrame 数组,并在每次迭代中执行以下操作:
    • 循环遍历每个文本框架中的ParagraphCollection。
    • 访问每个Paragraph 中的PartionCollection。
    • 检查Partion.Text 是否包含搜索字符串。
    • 如果是,找到搜索字符串的位置并通过设置Partion.Text属性替换它。
  • 使用Presentation.Save(string, SaveFormat)方法保存更新的演示文稿。

以下代码示例展示了如何在 PowerPoint 演示文稿中查找和替换文本。

// Load presentation
Presentation pres = new Presentation("mytextone.pptx");

string strToFind = "search string";
string strToReplaceWith = "replace string";

// Loop through each slide
foreach (Slide slide in pres.Slides)
{
    // Get all text frames in the slide
    ITextFrame[] tf = SlideUtil.GetAllTextBoxes(slide);

    for (int i = 0; i < tf.Length; i++) foreach (Paragraph para in tf[i].Paragraphs) foreach (Portion port in para.Portions) // Find text to be replaced if (port.Text.Contains(strToFind)) { // Replace exisitng text with the new text string str = port.Text; int idx = str.IndexOf(strToFind); string strStartText = str.Substring(0, idx); string strEndText = str.Substring(idx + strToFind.Length, str.Length - 1 - (idx + strToFind.Length - 1)); port.Text = strStartText + strToReplaceWith + strEndText; } } // Save the presentation pres.Save("myTextOneAspose.pptx", SaveFormat.Pptx);

如果您有任何疑问或需求,请随时加入Aspose技术交流群(761297826),我们很高兴为您提供查询和咨询