Java对pptx模板进行填充,前期可以找到文本进行替换,但是格式发生了变化,通过修改代码,达到填充模板不改变原有格式的效果。快餐时代,授之以渔不如授之以鱼,复制粘贴即可使用,废话少说,上代码
maven依赖如下:
<!--引入poi处理--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.3</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>5.2.3</version> </dependency>
代码如下,自行补全函数体就可以调用,放入main函数直接可以使用:
FileInputStream inputStream=new FileInputStream(new File("/home/xxx/demo.pptx")); XMLSlideShow pptx = new XMLSlideShow(inputStream); List<XSLFSlide> slideList=pptx.getSlides(); System.out.println("页数:"+slideList.size()); //遍历每个页面 for(XSLFSlide slide:slideList){ for(XSLFShape shape:slide.getShapes()){ //获取文字区域 if(shape instanceof XSLFTextShape){ XSLFTextShape textShape= (XSLFTextShape) shape; List<XSLFTextParagraph> textParagraphs = textShape.getTextParagraphs(); for(XSLFTextParagraph paragraph:textParagraphs){ for(XSLFTextRun run:paragraph.getTextRuns()){ String text= run.getRawText(); if(text.contains("${date}")){ text=text.replace("${date}","2023年7月14日"); run.setText(text); } } } } else if (shape instanceof XSLFTable) { //从表格中获取文字 XSLFTable table= (XSLFTable) shape; for(XSLFTableRow row:table.getRows()){ for(XSLFTableCell cell:row.getCells()) { List<XSLFTextParagraph> textParagraphs = cell.getTextParagraphs(); for (XSLFTextParagraph paragraph : textParagraphs) { for (XSLFTextRun run : paragraph.getTextRuns()) { String text = run.getRawText(); if (text.contains("${data}")) { text = text.replace("${date}","2023年7月14日"); run.setText(text); } } } } } }else{ } } } FileOutputStream out = new FileOutputStream(new File("/home/xxx/demo2.pptx")); pptx.write(out); out.close();
适用于pptx模板,要用ppt模板就自己改造一下。言尽于此。