Java实现根据模板自动生成新的PPT

作者:小小张自由—>张有博 时间:2022-10-22 18:31:31 

项目需求

最近项目中有一个需求就是让Java代码去代替人工操作,自动生成PPT,具体就是查询数据库数据,然后根据模板文件(PPT),将数据库数据与模板文件(PPT),进行组合一下。生成新的PPT文件。

模板文件如下

Java实现根据模板自动生成新的PPT

Java实现根据模板自动生成新的PPT

将模板文件中的姓名,进步率,连续进步次数,图片。替换为具体的人员信息。

实现过程

1.引入第三方依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15</version>
</dependency>

Apache POI   是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。POI为&ldquo;Poor Obfuscation Implementation&rdquo;的首字母缩写,意为&ldquo;简洁版的模糊实现&rdquo;。

HSSF-提供读写MicrosoftExcelXLS格式档案的功能

XSSF-提供读写MicrosoftExcelOOXMLXLSX格式档案的功能

HWPF-提供读写MicrosoftWordDOC格式档案的功能

HSLF-提供读写MicrosoftPowerPoint格式档案的功能

HDGF-提供读MicrosoftVisio格式档案的功能

HPBF-提供读MicrosoftPublisher格式档案的功能

HSMF-提供读MicrosoftOutlook格式档案的功能

2.编写业务代码


import org.apache.poi.sl.usermodel.Shape;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.xslf.usermodel.XMLSlideShow;

import java.io.*;
import java.util.List;

/**
* 读取模板PPT生成新的PPT文件
*
* @author Promsing(张有博)
* @version 1.0.0
* @since 2022/2/11 - 15:37
*/
public class RenderPowerPointTemplate extends BasePowerPointFileUtil {

/**
    * 读取PPT模板
    * @param powerPoint
    * @param
    * @throws IOException
    */
   public static void renderPowerPointTemplateOfCertificate(InputStream powerPoint, List<WeekAnalyseModel> lists, String rankType) throws IOException {
       //List<WeekAnalyseModel>是我们项目自己定义的model,可改成其他业务的model
       if(powerPoint == null) {
           return;
       }
       //创建一个幻灯片
       XMLSlideShow slideShow = new XMLSlideShow(powerPoint);
       //从幻灯片中获取每个页
       List slides = slideShow.getSlides();
       //遍历每一页PPT
       for (int i = 0 ; i < slides.size() ; i++) {
           //幻灯片布局,文本框,矩形框之类的,遍历一页PPT中的所有控件
           List shapes = ((Slide)slides.get(i)).getShapes();
           for (int j = 0 ; j < shapes.size() ; j++) {
               Shape shape = (Shape) shapes.get(j);
               RenderPowerPointTemplate.renderShapeAndPicture(shape, lists.get(i),rankType);
           }
       }

//新PPT的位置,file就是新的PPT文件
       File file=new File(rankType+"test.pptx");
       OutputStream outputStreams = new FileOutputStream(file);
       slideShow.write(outputStreams);
      // FileUpLoadUtil.T_THREAD_LOCAL.set(file.getAbsolutePath());
       System.out.println("新文件的路径:"+file.getAbsolutePath());

}
}

import com.tfjybj.integral.constant.CommonConstant;
import com.tfjybj.integral.model.WeekAnalyseModel;
import com.tfjybj.integral.utils.SimplifiedDate;
import org.apache.commons.io.FileUtils;
import org.apache.poi.sl.usermodel.Shape;
import org.apache.poi.sl.usermodel.*;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
* <p>PowerPoint文件工具基类
* <p>
* <p>通用的PowerPoint文件工具基类,可用于从PowerPoint文档中抽取文本信息
*/
public class BasePowerPointFileUtil {

/**
    * 渲染、绘制文本框
    *
    * @param shape
    * @param data
    */
   public static void renderShapeAndPicture(Shape shape, WeekAnalyseModel data,String rankType) {
       //判断是否是文本框
       if (shape instanceof TextShape) {
           BasePowerPointFileUtil.replace(shape, data,rankType);
       } else if (shape instanceof GroupShape) {
           Iterator groupShapes = ((GroupShape) shape).iterator();
           while (groupShapes.hasNext()) {
               Shape groupShape = (Shape) groupShapes.next();
               BasePowerPointFileUtil.renderShapeAndPicture(groupShape, data,rankType);
           }
       } else if (shape instanceof TableShape) {
           TableShape tableShape = ((TableShape) shape);
           int column = tableShape.getNumberOfColumns();
           int row = tableShape.getNumberOfRows();
           for (int r = 0; r < row; r++) {
               for (int c = 0; c < column; c++) {
                   BasePowerPointFileUtil.replace(tableShape.getCell(r, c), data,rankType);
               }
           }
       } else if (shape instanceof PictureShape) {
           //判断是否是图片框
           PictureShape pictureShape = (PictureShape) shape;
           PictureData pictureData = pictureShape.getPictureData();
           byte[] bytes = BufferStreamForByte(URLToFile(data.getPictureURL()), 1024);
           try {
               pictureData.setData(bytes);
           } catch (IOException e) {
               e.printStackTrace();
           }
       }

}

/**
    * 替换模板PPT中的值
    *
    * @param shape
    * @param weekAnalyseModel
    */
   public static void replace(Shape shape, WeekAnalyseModel weekAnalyseModel,String rankType) {
        //List<WeekAnalyseModel>是我们项目自己定义的model,可改成其他业务的model
       if (shape instanceof TextShape) {

String replaceText = ((XSLFTextShape) shape).getText();
           XSLFTextRun xslfTextRun = null;
           //替换数据的业务逻辑,待优化
           switch (replaceText) {
               case "姓名:闪耀姓名1":
                   xslfTextRun = ((XSLFTextShape) shape).setText("姓名:" + weekAnalyseModel.getUserName());
                   break;
               case "积分:闪耀分数1":
                   xslfTextRun = ((XSLFTextShape) shape).setText("积分:" + weekAnalyseModel.getWeekData());
                   break;
               case "闪耀1连击ヾ":
                   xslfTextRun = ((XSLFTextShape) shape).setText("闪耀" + weekAnalyseModel.getListNumber() + "连击ヾ");
                   break;
               case "姓名:闪耀姓名2":
                   xslfTextRun = ((XSLFTextShape) shape).setText("姓名:" + weekAnalyseModel.getUserName());
                   break;
               case "积分:闪耀分数2":
                   xslfTextRun = ((XSLFTextShape) shape).setText("积分:" + weekAnalyseModel.getWeekData());
                   break;
               case "闪耀2连击ヾ":
                   xslfTextRun = ((XSLFTextShape) shape).setText("闪耀" + weekAnalyseModel.getListNumber() + "连击ヾ");
                   break;

}

//空值过滤,设置样式
           if (xslfTextRun != null) {
               if (rankType.equals("闪耀之星")||rankType.equals("进步之星")){
                   setTextStyle(xslfTextRun);
               }else if (rankType.equals("闪耀之星荣誉证书")||rankType.equals("进步之星荣誉证书")){
                   setTextStyleCertificate(xslfTextRun);
               }
           }
       }
   }

/**
    * 设置字体样式
    *
    * @param xslfTextRun
    */
   private static void setTextStyle(XSLFTextRun xslfTextRun) {
       xslfTextRun.setFontFamily("等线(正文)");
       Color color = new Color(255, 255, 255);
       xslfTextRun.setFontColor(color);
       xslfTextRun.setFontSize(40.0);
       xslfTextRun.setBold(true);
   }

/**
    * 设置证书字体样式
    *
    * @param xslfTextRun
    */
   private static void setTextStyleCertificate(XSLFTextRun xslfTextRun) {
       xslfTextRun.setFontFamily("宋体");
       Color color = new Color(0, 0, 0);
       xslfTextRun.setFontColor(color);
       xslfTextRun.setFontSize(32.0);
       xslfTextRun.setBold(true);
   }

/**
    * 将文件转为字节数组
    * @param file
    * @param size
    * @return
    */
   public static byte[] BufferStreamForByte(File file, int size) {
       byte[] content = null;
       try {
           BufferedInputStream bis = null;
           ByteArrayOutputStream out = null;
           try {
               FileInputStream input = new FileInputStream(file);
               bis = new BufferedInputStream(input, size);
               byte[] bytes = new byte[1024];
               int len;
               out = new ByteArrayOutputStream();
               while ((len = bis.read(bytes)) > 0) {
                   out.write(bytes, 0, len);
               }

bis.close();
               content = out.toByteArray();
           } finally {
               if (bis != null) {
                   bis.close();
               }
               if (out != null) {
                   out.close();
               }
           }
       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       return content;

}

/**
    * 读取网络中的图片
    * @param url https://www.kziyue.com/wp-content/uploads/2019/06/5bca-hxyuaph9825616.jpg
    * @return
    */
   public static File URLToFile(String url){
       File file1 = new File("test.mp4");
       try {

URL url1 = new URL(url);
           FileUtils.copyURLToFile(url1,file1);

} catch (IOException e) {
           e.printStackTrace();
       }
       File absoluteFile = file1.getAbsoluteFile();
       return file1;
   }

}

3.根据模板生成新的PPT

Java实现根据模板自动生成新的PPT

来源:https://blog.csdn.net/promsing/article/details/122876796

标签:Java,模板,PPT
0
投稿

猜你喜欢

  • Android四种数据存储的应用方式

    2023-07-25 05:01:06
  • 复杂JSON字符串转换为Java嵌套对象的实现

    2023-07-02 05:40:26
  • java.sql.Date和java.util.Date的区别详解

    2023-11-28 16:15:09
  • Java properties 和 yml 的区别解析

    2023-04-01 22:28:09
  • MyBatis字段名和属性名不一致的解决方法

    2022-12-15 18:15:22
  • MFC程序设计常用技巧汇总

    2023-11-02 20:37:12
  • 在Spring环境中正确关闭线程池的姿势

    2023-11-25 08:07:29
  • Java使用Thread和Runnable的线程实现方法比较

    2021-11-17 07:52:54
  • Java 自定义Spring框架以及Spring框架的基本使用

    2021-05-29 19:35:57
  • 详解SpringMVC如何进行数据回显

    2023-09-12 08:48:15
  • springboot整合solr的方法详解

    2023-01-20 17:54:37
  • 计算一个Java对象占用字节数的方法

    2022-06-14 18:05:21
  • 详解AngularJs与SpringMVC简单结合使用

    2023-10-22 04:19:08
  • IDEA启动tomcat控制台中文乱码问题的解决方法(100%有效)

    2021-06-25 10:45:23
  • Java字节与字符流永久存储json数据

    2022-12-27 21:10:13
  • Spring AOP如何整合redis(注解方式)实现缓存统一管理详解

    2023-11-19 06:09:27
  • SpringCloud之微服务容错的实现

    2023-11-29 02:02:22
  • Java 实现判定顺序表中是否包含某个元素(思路详解)

    2023-09-11 01:03:04
  • spring-mybatis获取mapper的四种方式汇总

    2023-11-23 06:24:39
  • Java中常见的查找算法与排序算法总结

    2021-07-14 13:21:23
  • asp之家 软件编程 m.aspxhome.com