本文介绍如何使用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)));
}
}
}
}
}
}
}