根据模板生成PPT

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

假设模板如下:
注意:需要一个一个输入框(进步姓名和进步成绩分开往ppt里面写)的往ppt里面输入,因为代码里面一个输入框表示一个对象
在这里插入图片描述

在这里插入图片描述

1.依赖


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

<!-- 文件操作工具类FileUtils-->
 <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
 </dependency>
HSSF-提供读写MicrosoftExcelXLS格式档案的功能  --  excel
XSSF-提供读写MicrosoftExcelOOXMLXLSX格式档案的功能 -- excel(07以上)
HWPF-提供读写MicrosoftWordDOC格式档案的功能 -- word
HSLF-提供读写MicrosoftPowerPoint格式档案的功能  --  ppt
HDGF-提供读MicrosoftVisio格式档案的功能  --  流程图
HPBF-提供读MicrosoftPublisher格式档案的功能 -- 桌面应用
HSMF-提供读MicrosoftOutlook格式档案的功能 -- 邮件

2.使用

2.1 ppt数据的实体类


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author lc
 * @version 1.0
 * @date 2022/3/29 9:48
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WeekAnalyseModel {

    private String userName; // 名字
    private int weekData; // 积分
    private int listNumber; // 闪耀
    private String pictureURL; // 图片
}

2.2 实现接口

import com.zykj.healthcode.pojo.WeekAnalyseModel;
import org.apache.poi.sl.usermodel.Shape;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.List;
 
/**
 * 读取模板PPT生成新的PPT文件
 *
 * @author Promsing(张有博)
 * @version 1.0.0
 * @since 2022/2/11 - 15:37
 */
 @RestController
public class RenderPowerPointTemplate extends BasePowerPointFileUtil {
 
    /**
     * 读取PPT模板
     * @param powerPoint  - ppt的输入流,rankType存储的符盘路径, lists--ppt里面想要存放的数据
     * @param 
     * @throws IOException
     */
    //public static void renderPowerPointTemplateOfCertificate(InputStream powerPoint, List<WeekAnalyseModel> lists, String rankType) throws IOException {
    @RequestMapping("/test")
     public void renderPowerPointTemplateOfCertificate() 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);
				// 假如的数据
				WeekAnalyseModel weekAnalyseModel = new WeekAnalyseModel();
                weekAnalyseModel.setUserName("测试");
                weekAnalyseModel.setWeekData(1);
                
                //RenderPowerPointTemplate.renderShapeAndPicture(shape, lists.get(i),rankType);
                RenderPowerPointTemplate.renderShapeAndPicture(shape, weekAnalyseModel,"E:\\");
            }
        }
 
        //新PPT的位置,file就是新的PPT文件
        //File file=new File(rankType+"test.pptx");
		File file=new File("E:\\"+"test.pptx");
        OutputStream outputStreams = new FileOutputStream(file);
        slideShow.write(outputStreams);
       // FileUpLoadUtil.T_THREAD_LOCAL.set(file.getAbsolutePath());
        System.out.println("新文件的路径:"+file.getAbsolutePath());
 
 
    }
}

2.3 工具类

 
import com.zykj.healthcode.pojo.WeekAnalyseModel;
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.Iterator;
 
/**
 * <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 "进步姓名:":
                    xslfTextRun = ((XSLFTextShape) shape).setText("进步姓名:" + weekAnalyseModel.getUserName());
                    break;
                case "进步成绩:":
                    xslfTextRun = ((XSLFTextShape) shape).setText("进步成绩:" + weekAnalyseModel.getWeekData());
                    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

调用接口:http://localhost:9551/test

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LC超人在良家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值