POI处理PPTX模板,保持格式不变

该文章介绍了如何使用Java的ApachePOI库来填充PPTX模板,同时确保不改变原有的格式。通过读取模板文件,遍历幻灯片和形状,查找并替换特定文本,然后保存到新的PPTX文件中,实现了文本替换功能,特别是针对文本框和表格中的内容。
摘要由CSDN通过智能技术生成

     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模板就自己改造一下。言尽于此。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值