Java 在 PowerPoint 中查找和替換文本

MS PowerPoint 提供了一個有用的功能,可以在演示文稿中查找和替換文本。但是,您可能需要自動化來對一批文件執行此操作。因此,在本文中,您將學習如何使用 Java 以編程方式在 PowerPoint PPTX/PPT 中查找和替換文本。

用於在 PowerPoint 中查找和替換文本的 Java API

為了在 PPTX/PPT 演示文稿中查找和替換文本,我們將使用 Aspose.Slides for Java。它是一個強大的 API,用於在您的 Java 應用程序中創建、操作和轉換 PowerPoint 演示文稿。您可以 下載 API 或使用以下 Maven 配置安裝它。

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>http://repository.aspose.com/repo/</url>
</repository>
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-slides</artifactId>
    <version>21.7</version>
    <classifier>jdk16</classifier>
</dependency>

使用 Java 在 PowerPoint PPTX 中查找和替換文本

以下是使用 Java 在 PPTX 演示文稿中查找和替換文本的步驟。

以下代碼示例演示如何查找和替換 PowerPoint 演示文稿中的文本。

// 負載演示
Presentation pres = new Presentation("mytextone.pptx");

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

// 遍歷每張幻燈片
for (ISlide slide : pres.getSlides()) {
	// 獲取幻燈片中的所有文本框
	ITextFrame[] tf = SlideUtil.getAllTextBoxes(slide);

	for (int i = 0; i < tf.length; i++)

		for (IParagraph para : tf[i].getParagraphs())

			for (IPortion port : para.getPortions())

				// 查找要替換的文本
				if (port.getText().contains(strToFind)) {
					// 用新文本替換現有文本
					String str = port.getText();
					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.setText(strStartText + strToReplaceWith + strEndText);

				}
}

// 保存演示文稿
pres.save("myTextOneAspose.pptx", SaveFormat.Pptx);

獲取免費的 API 許可證

通過申請臨時許可,您可以在沒有評估限制的情況下使用 Aspose.Slides for Java。

結論

在本文中,您學習瞭如何使用 Java 以編程方式查找和替換 PowerPoint 演示文稿中的文本。您可以簡單地將 API 和提供的代碼示例集成到您的 Java 應用程序中。此外,您可以訪問 文檔 來探索 Aspose.Slides for Java 的其他功能。此外,您可以通過我們的 論壇 讓我們知道您的疑問。

也可以看看