本文介绍如何使用Spire.Presentation for Java替换PowerPoint文档中的文本。
import com.spire.presentation.*;
import java.util.HashMap;
import java.util.Map;
public class ReplaceText {
public static void main(String[] args) throws Exception {
//创建Presentation对象
Presentation presentation = new Presentation();
//加载示例文档
presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.pptx");
//获取第一张幻灯片
ISlide slide= presentation.getSlides().get(0);
//创建Map对象
Map map = new HashMap();
//将需要被替换和用于替换的文本以键值的形式添加到Map
map.put("#姓名#","小明");
map.put("#年龄#","28");
map.put("#地址#","成都市");
map.put("#电话#","028-12345678");
map.put("#邮箱#","xiaoming @163.com");
//替换幻灯片中的文本
replaceText(slide,map);
//保存文档
presentation.saveToFile("output/ReplaceText.pptx", FileFormat.PPTX_2013);
}
/**
* 替换指定幻灯片中的文本
* @param slide指定幻灯片
* @param map以键值的形式存储需要被替换和用于替换的文本
*/
public static void replaceText(ISlide slide, Map map) {
for (Object shape : slide.getShapes()
) {
if (shape instanceof IAutoShape) {
for (Object paragraph : ((IAutoShape) shape).getTextFrame().getParagraphs()
) {
ParagraphEx paragraphEx = (ParagraphEx)paragraph;
for (String key : map.keySet()
) {
if (paragraphEx.getText().contains(key)) {
paragraphEx.setText(paragraphEx.getText().replace(key, map.get(key)));
}
}
}
}
}
}
}