在工作中遇到将数据导入设置好的ppt模板内的需求,用来记录所学心得,它的原理就是我们先准备好一页ppt,上面有文本框和形状框,但是需要注明它的名字,以便我们的Java代码识别,我们的poi读取到ppt模板,而后根据读取的各种形状、形状名字,将我们的数据填充进去,实现对ppt文件进行操作的类包主要是HSLF(.ppt)和XSLF(.pptx),两个的区别就是版本的区别,看各自office的版本,使用哪个类,本文主要是XSLF
// 加载模板PPTX文件
InputStream template = new FileInputStream(profile);
String text = new PowerPointExtractor(template).getText();
XMLSlideShow ppt = new XMLSlideShow(template);
// 获取模板的主幻灯片
XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);
XSLFSlideLayout slideLayout = slideMaster.getLayout(SlideLayout.TITLE);
// 创建新的幻灯片
XSLFSlide slide = ppt.createSlide(slideLayout);
// 获取幻灯片的文本框并设置内容
XSLFTextShape title = slide.getPlaceholder(0);
System.out.println(title.getText());
title.setText("Hello, World!");
title.setText("Hello, World!");
title.setFillColor(Color.RED);
System.out.println(title.getText());
FileOutputStream output = new FileOutputStream(profile);
ppt.write(output);
output.close();
System.out.println("PPTX文件生成成功!");
public static void main(String[] args) throws Exception {
String pptPath = "文件路径.pptx";
FileInputStream fileInputStream = new FileInputStream(pptPath);
XMLSlideShow xmlSlideShow = new XMLSlideShow(fileInputStream);
XSLFSlide xslfShapes = xmlSlideShow.getSlides().get(0);
for (int i = 0; i < 4; i++) {
XSLFSlide slide = xmlSlideShow.createSlide();
slide.importContent(xslfShapes);
}
FileOutputStream outputStream = new FileOutputStream("文件路径地址.pptx");
xmlSlideShow.write(outputStream);
outputStream.close();
xmlSlideShow.close();
}