第一次使用org.apache.poi做ppt导出,随手记录下。
依赖导入:
使用版本: org.apache.poi:poi-ooxml:5.2.0
https://search.maven.org/artifact/org.apache.poi/poi-ooxml/5.2.0/jar
打开地址 在左上角选取版本,在右侧复制依赖引入。 我这里实用的是Gradle
实际使用中 除了poi_ooxml外,还要引入几个依赖,否则会导致编译报错,xxxx函数找不到。共需引入4个依赖包,如下:
//poi-ooxml implementation 'org.apache.poi:poi-ooxml:5.2.0' implementation 'org.apache.poi:poi:5.2.0' implementation 'commons-io:commons-io:2.11.0' implementation 'org.apache.logging.log4j:log4j-api:2.17.1'
使用:
XMLSlideShow读取或者新建ppt:
这个类表示ppt本身,提供了多个构造函数,这里我们使用带参数的构造函数来读取ppt模板:
//加载模板 File file = new File(“D:\\opencv\\template\\template.pptx”); FileInputStream fileInputStream = new FileInputStream(file); //加载ppt演示文稿模板 XMLSlideShow ppt = new XMLSlideShow(fileInputStream);
这个类也提供了无参构造,用于新建一个全新的ppt
XSLFSlide读取或新建幻灯片:
这个类表示幻灯片,每一个对象是一张幻灯片。由于我们使用的是准备好的模板,所以通过XMLSlideShow对象来获取模板中的幻灯片列表
//读取ppt中的幻灯片
List<XSLFSlide> xslfSlideList = ppt.getSlides();
XSLFSlide frontPage = xslfSlideList.get(0);
使用XSLFTextBox添加文字:
用于添加文字:
//向幻灯片中插入文字
XSLFTextBox xslfTextBox = frontPage.createTextBox(); xslfTextBox.appendText(“此处填写文字内容”, true);
//文字位置(文字框左上角坐标 450, 74 。 文字框宽高 280, 43) Rectangle2D rectText = new Rectangle2D.Double(450, 74, 280, 43); xslfTextBox.setAnchor(rectText);
使用XSLFPictureData向添加图片:
用于插入图片:
//获取图片文件 File image=new File("E:\\IMG0002_1628151287000_4a82632842924f3bbaf72bd64d744464.JPG"); byte[] picture = IOUtils.toByteArray(new FileInputStream(image)); //将图片加入ppt演示文稿 XSLFPictureData pictureData = ppt.addPicture(picture, PictureData.PictureType.JPEG);
//把图片插入幻灯片并设置图片位置和大小 XSLFPictureShape pic = frontPage.createPicture(pictureData);
Rectangle2D rectImage = new Rectangle2D.Double(20, 20, 200, 200)
pic.setAnchor(rectImage);
输出ppt文件:
//输出新的演示文稿 File outFile=new File("D:\\opencv\\template\\addingimage.pptx"); FileOutputStream out = new FileOutputStream(outFile); ppt.write(out); out.close();
PS: 还有其他诸如占位符替换等操作,有时间的话后面会再整理一篇文章。