使用poi替换ppt文件内的变量参数,包含ppt和pptx格式
依赖的jar包
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>xdocreport</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
package pptreplace;
import convert.uuid.UuidUtil;
import org.apache.poi.hslf.record.Slide;
import org.apache.poi.hslf.usermodel.HSLFShape;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hslf.usermodel.HSLFTextShape;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
import java.awt.geom.Rectangle2D;
import java.io.*;
import java.util.List;
public class PptxReplaceTest {
public static void main(String[] args) throws IOException {
// // 获取PPT文件
// FileInputStream is = new FileInputStream("D:\\2.pptx"); //读pptx存放的路径
// XMLSlideShow ppt = new XMLSlideShow(is);
// is.close();
// for (XSLFSlide slide : ppt.getSlides()) {
// // 获取每一张幻灯片中的shape
// for (XSLFShape shape : slide.getShapes()) {
// if (shape instanceof XSLFTextShape) {
// XSLFTextShape txShape = (XSLFTextShape) shape;
// if (txShape.getText().contains("{time}")) {
// // 替换文字内容
// txShape.setText(txShape.getText().replace(
// "{time}", "time1"));
// }
// }
// }
// }
FileInputStream is = new FileInputStream("C:\\Users\\Desktop\\11.ppt");
SlideShow ppt = new HSLFSlideShow(is);
List<HSLFSlide> slides = ppt.getSlides();
for(HSLFSlide slide : slides){
List<HSLFShape> shapes = slide.getShapes();
for (HSLFShape shape : shapes){
if(shape instanceof HSLFTextShape){
HSLFTextShape textShape = (HSLFTextShape) shape;
if(textShape.getText().contains("{{test}}")){
textShape.setText(textShape.getText().replace("{{test}}","chaoping amazing"));
}
}
}
}
String filename = "C:\\Users\\Desktop\\" + UuidUtil.getUUID() + ".ppt";
System.out.println(filename);
FileOutputStream out = new FileOutputStream(filename);
ppt.write(out);
out.close();
// FileOutputStream out = new FileOutputStream("ppt测试.ppt");
// ppt.write(out);
// out.close();
}
}