JAVA根据模板导出PPTX

1、使用PowerPoint新建一个PPTX模板,每个${}占一块,否则模板容易报错,模板图片添加的是jpeg,图片从上到下1,2,3…,keyValueMap.put(“image1.jpeg”, imageEntity);(模板路径:https://download.csdn.net/download/xionglangs/23512543)
在这里插入图片描述

package com.utils;

import cn.afterturn.easypoi.entity.ImageEntity;
import com.google.common.collect.Lists;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.xslf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

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

/**
 * Description:
 *
 * @Author: leo.xiong
 * @CreateDate: 2021/8/30 12:13
 * @Email: [email protected]
 * @Since:
 */
public class PptUtil {
    
    
    private static final Logger LOGGER = LoggerFactory.getLogger(PptUtil.class);
    public static final String TITLE = "title";
    /**
     * 首页内容
     */
    public static final String FIRST_CONTENT = "firstContent";
    /**
     * 首页位置 Rectangle,x轴坐标,y轴坐标,宽度,高度
     */
    public static final String ANCHOR = "anchor";
    /**
     * 图片信息
     */
    public static final String IMAGE = "image";

    public static final String CATALOG = "catalog";
    public static final String PREFIX = "${";
    public static final String SUFFIX = "}";

    public static final String IMAGE_SUFFIX = ".jpeg";

    public static String exportPpt(File file, Map<String, Object> keyValueMap) {
    
    
        //创建ppt对象
        XMLSlideShow ppt = new XMLSlideShow();
        //首页
        XSLFSlide slideFirst = ppt.createSlide();
        Map<String, Object> firstValueMap = (Map<String, Object>) keyValueMap.get(FIRST_CONTENT);
        fillFirstContent(slideFirst, firstValueMap);
        //目录
        XSLFSlide slideCatalog = ppt.createSlide();
        Map<String, Object> keyCatalogMap = (Map<String, Object>) keyValueMap.get(CATALOG);
        List<XSLFSlide> contentSlides = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(keyCatalogMap)) {
    
    
            keyCatalogMap.forEach((key, content) -> {
    
    
                contentSlides.add(ppt.createSlide());
            });
        }
        fillCatalog(slideCatalog, contentSlides, keyCatalogMap);
        Map<String, List<ImageEntity>> imageEntityListMap = (Map<String, List<ImageEntity>>) keyValueMap.get(IMAGE);
        fillContent(contentSlides, keyCatalogMap, imageEntityListMap, ppt);
        StringBuffer fileUrl = new StringBuffer();
        fileUrl.append(file.getName());
        fileUrl.append(file.getName());
        FileOutputStream out = null;
        try {
    
    
            file = new File(fileUrl.toString());
            out = new FileOutputStream(file);
            ppt.write(out);
        } catch (FileNotFoundException e) {
    
    
            LOGGER.error("文件创建失败,请尝试给web目录赋权777");
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                if (out != null) {
    
    
                    out.close();
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        return file.getName();
    }

    /**
     * 填充正文,包含图片
     *
     * @param contentSlides
     * @param keyCatalogMap
     * @param imageEntityListMap
     * @param ppt
     */
    private static void fillContent(List<XSLFSlide> contentSlides, Map<String, Object> keyCatalogMap, Map<String, List<ImageEntity>> imageEntityListMap, XMLSlideShow ppt) {
    
    
        if (contentSlides != null) {
    
    
            List<String> titles = (List<String>) keyCatalogMap.get(TITLE);
            int len = contentSlides.size();
            for (int i = 0; i < len; i++) {
    
    
                createTitle(contentSlides.get(i), titles.get(i));
                List<ImageEntity> entityList = imageEntityListMap.get(titles.get(i));
                if (CollectionUtils.isEmpty(entityList)) {
    
    
                    continue;
                }
                for (ImageEntity imageEntity : entityList) {
    
    
                    createPicture(contentSlides.get(i), imageEntity.getUrl(), ppt, i);
                }
            }
        }
    }

    /**
     * 填充时间
     *
     * @param xslfSlide
     * @param picCreateTime
     */
    private static void createTime(XSLFSlide xslfSlide, String picCreateTime) {
    
    
        //标题文本框
        XSLFTextBox xslfTextBox = xslfSlide.createTextBox();
        xslfTextBox.setAnchor(new Rectangle(400, 460, 300, 80));
        xslfTextBox.setFlipHorizontal(true);
        //段落
        XSLFTextParagraph paragraph0 = xslfTextBox.addNewTextParagraph();
        paragraph0.setTextAlign(TextParagraph.TextAlign.LEFT);
        XSLFTextRun xslfTextRun = paragraph0.addNewTextRun();
        xslfTextRun.setFontSize(18D);
        //宋体 (正文)
        xslfTextRun.setFontFamily("宋体");
        String text = "123";
        xslfTextRun.setText(String.format(text, picCreateTime));
    }

    /**
     * 填充图片
     *
     * @param slide
     * @param picturePath
     * @param ppt
     * @param flag
     */
    private static void createPicture(XSLFSlide slide, String picturePath, XMLSlideShow ppt, int flag) {
    
    
        try {
    
    
            byte[] pictureData = IOUtils.toByteArray(new FileInputStream(picturePath));
            XSLFPictureData pictureIndex = ppt.addPicture(pictureData, PictureData.PictureType.JPEG);
            XSLFPictureShape pictureShape = slide.createPicture(pictureIndex);
            if (flag == 4) {
    
    
                pictureShape.setAnchor(new Rectangle(125, 100, 467, 200));
            } else {
    
    
                pictureShape.setAnchor(new Rectangle(125, 100, 467, 350));
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 目录填充
     *
     * @param xslfSlide
     * @param catalogMap
     */
    private static void fillCatalog(XSLFSlide xslfSlide, List<XSLFSlide> contentSlides, Map<String, Object> catalogMap) {
    
    
        createTitle(xslfSlide, "目录");
        //内容文本框
        XSLFTextBox xslfTextBox = xslfSlide.createTextBox();

        xslfTextBox.setAnchor((Rectangle) catalogMap.get(ANCHOR));
        xslfTextBox.setFlipHorizontal(true);
        //段落
        XSLFTextParagraph paragraph = xslfTextBox.addNewTextParagraph();
        paragraph.setTextAlign(TextParagraph.TextAlign.LEFT);
        List<String> titles = (List<String>) catalogMap.get(TITLE);
        if (CollectionUtils.isEmpty(titles)) {
    
    
            return;
        }
        for (int i = 0, len = titles.size(); i < len; i++) {
    
    
            XSLFTextRun xslfTextRun = paragraph.addNewTextRun();
            xslfTextRun.setUnderlined(true);
            xslfTextRun.setFontSize(36D);
            xslfTextRun.setFontFamily("宋体");
            xslfTextRun.setText(i + 1 + "、" + titles.get(i));
            xslfTextRun.createHyperlink().setAddress(contentSlides.get(i).toString());
        }
    }

    /**
     * 生成标题头
     *
     * @param xslfSlide
     * @param title
     */
    private static void createTitle(XSLFSlide xslfSlide, String title) {
    
    
        //标题文本框
        XSLFTextBox xslfTextBox = xslfSlide.createTextBox();
        xslfTextBox.setAnchor(new Rectangle(10, 25, 700, 85));
        xslfTextBox.setFlipHorizontal(true);
        //段落
        XSLFTextParagraph paragraph0 = xslfTextBox.addNewTextParagraph();
        paragraph0.setTextAlign(TextParagraph.TextAlign.CENTER);
        XSLFTextRun xslfTextRun = paragraph0.addNewTextRun();
        xslfTextRun.setFontSize(44D);
        //黑体
        xslfTextRun.setFontFamily("宋体");
        xslfTextRun.setBold(true);
        xslfTextRun.setText(title);
    }

    /**
     * 填充首页内容
     *
     * @param xslfSlide
     * @param firstValueMap
     */
    private static void fillFirstContent(XSLFSlide xslfSlide, Map<String, Object> firstValueMap) {
    
    
        //文本框
        XSLFTextBox xslfTextBox = xslfSlide.createTextBox();
        //坐标,x轴,y轴,宽度,高度
        xslfTextBox.setAnchor((Rectangle) firstValueMap.get(ANCHOR));
        xslfTextBox.setFlipHorizontal(true);
        //段落
        XSLFTextParagraph paragraph = xslfTextBox.addNewTextParagraph();
        paragraph.setTextAlign(TextParagraph.TextAlign.CENTER);
        //标题
        XSLFTextRun xslfTextRun = paragraph.addNewTextRun();
        xslfTextRun.setBold(true);
        xslfTextRun.setFontSize(44D);
        //宋体 (标题)
        xslfTextRun.setFontFamily("宋体");
        xslfTextRun.setText((String) firstValueMap.get(TITLE));
    }

    public static byte[] getFileToByte(File file) {
    
    
        byte[] bytes = new byte[(int) file.length()];
        try {
    
    
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            byte[] bb = new byte[2048];
            int ch;
            ch = is.read(bb);
            while (ch != -1) {
    
    
                byteStream.write(bb, 0, ch);
                ch = is.read(bb);
            }
            bytes = byteStream.toByteArray();
        } catch (Exception ex) {
    
    
            ex.printStackTrace();
        }
        return bytes;
    }

    /**
     * 导出XML
     *
     * @param tempPath
     * @param tempName
     * @param exportPath
     * @param keyValueMap
     * @throws IOException
     */
    public static void exportXML(String tempPath, String tempName, String exportPath, Map<String, Object> keyValueMap) throws IOException {
    
    
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDirectoryForTemplateLoading(new File(tempPath));
        //读取模板路径下的PPT的.xml模板文件
        Template template = configuration.getTemplate(tempName, "UTF-8");
        //设置导出路径
        File outfile = new File(exportPath);
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile)), 10240);
        try {
    
    
            //将数据替换并导出PPT
            template.process(keyValueMap, out);
        } catch (TemplateException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            out.close();
        }
    }

    /**
     * 导出PPT
     *
     * @param dir
     * @param tempName
     * @param downLoadPath
     * @param keyValueMap
     * @throws IOException
     */
    public static void exportPPT(String dir, String tempName, String downLoadPath, Map<String, Object> keyValueMap) throws IOException {
    
    
        XMLSlideShow ppt = null;
        FileOutputStream out = null;
        try {
    
    
            ppt = new XMLSlideShow(new FileInputStream(dir + "/" + tempName));
            for (int i = 0; i < ppt.getSlides().size(); i++) {
    
    
                XSLFSlide slides = ppt.getSlides().get(i);
                List<XSLFShape> shapes = slides.getShapes();
                // 遍历PPT的图形
                for (XSLFShape shape : shapes) {
    
    
                    if (shape instanceof XSLFTextShape) {
    
    
                        // 判断该图形类是否是文本框类
                        // 将图像类强制装换成文本框类
                        XSLFTextShape ts = (XSLFTextShape) shape;
                        // 替换文本框内的文字
                        ts.setText((String) replace(ts.getText(), keyValueMap));
                    } else if (shape instanceof XSLFTable) {
    
    
                        // 判断该图形类是否是表格类
                        // 将图像类强制装换成表格类
                        XSLFTable table = (XSLFTable) shape;
                        // 获取表格中的所有行
                        List<XSLFTableRow> rows = table.getRows();
                        for (XSLFTableRow tr : rows) {
    
    
                            // 获取行中的所有单元格
                            List<XSLFTableCell> cells = tr.getCells();
                            for (XSLFTableCell tc : cells) {
    
    
                                //替换单元格信息
                                tc.setText((String) replace(tc.getText(), keyValueMap));
                            }
                        }
                    } else if (shape instanceof XSLFPictureShape) {
    
    
                        // 判断该图形类是否是图片框类
                        // 将图像类强制装换成图片框类
                        XSLFPictureShape ps = (XSLFPictureShape) shape;
                        //替换图片信息
                        String fileName = PREFIX + ps.getPictureData().getFileName() + SUFFIX;
                        ps.getPictureData().setData((byte[]) replace(fileName, keyValueMap));
                    }
                }
            }
            File file = new File(downLoadPath);
            out = new FileOutputStream(file);
            ppt.write(out);

        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (out != null) {
    
    
                out.close();
            }
            if (ppt != null) {
    
    
                ppt.close();
            }
        }
    }

    /**
     * 替换信息
     *
     * @param tempKey
     * @param keyValueMap
     * @return
     */
    private static Object replace(String tempKey, Map<String, Object> keyValueMap) {
    
    
        for (Map.Entry<String, Object> keyValue : keyValueMap.entrySet()) {
    
    
            String key = PREFIX + keyValue.getKey() + SUFFIX;
            Object value = keyValue.getValue();
            if (tempKey.contains(key)) {
    
    
                if (value instanceof String) {
    
    
                    tempKey = tempKey.replace(key, value == null ? "" : (String) value);
                } else if (value instanceof ImageEntity) {
    
    
                    return ((ImageEntity) value).getData();
                }
            }
        }
        return tempKey;
    }
}

package com.test;

import cn.afterturn.easypoi.entity.ImageEntity;
import com.google.common.collect.Maps;
import com.suyun.modules.testdata.model.entity.ChartStyleValue;
import com.suyun.modules.testdata.model.entity.DmasChartData;
import com.utils.ChartUtils;
import com.utils.PptUtil;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.SeriesRenderingOrder;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeriesCollection;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description:
 *
 * @Author: leo.xiong
 * @CreateDate: 2021/9/7 17:14
 * @Email: [email protected]
 * @Since:
 */
public class exportPPT {
    
    
    public static void main(String[] args) throws IOException {
    
    
        Map<String, Object> keyValueMap = Maps.newHashMap();
        keyValueMap.put("currentDate", "2021-09-07");
        keyValueMap.put("productSerial", "211P-DL3-1-001");
        keyValueMap.put("runTime", "2614.7");
//        ImageEntity imageEntity = createImage("");
//        BASE64Encoder base64Encoder = new BASE64Encoder();
        //imageEntity.setData(PptUtil.getFileToByte(new File("C:/Users/熊浪/Desktop/20210611/RESULTS/Cell_voltage_vs_Stack_current_2.jpeg")));
//        String base64EncoderValue = base64Encoder.encode(imageEntity.getData());
        keyValueMap.put("image1.jpeg", createImage("1"));
        keyValueMap.put("averageCellVoltageTimeImageWidth", 300);
        keyValueMap.put("averageCellVoltageTimeImageHeight", 500);

        keyValueMap.put("image2.jpeg", createImage("2"));
        keyValueMap.put("averageCellVoltageStackCurrentImageWidth", 300);
        keyValueMap.put("averageCellVoltageStackCurrentImageHeight", 500);

        keyValueMap.put("image3.jpeg", createImage("3"));
        keyValueMap.put("upperCellVoltageStackCurrentImageWidth", 300);
        keyValueMap.put("upperCellVoltageStackCurrentImageHeight", 500);

        keyValueMap.put("image4.jpeg", createImage("4"));
        keyValueMap.put("lowerCellVoltageStackCurrentImageWidth", 300);
        keyValueMap.put("lowerCellVoltageStackCurrentImageHeight", 500);

        keyValueMap.put("image5.jpeg", createImage("5"));
        keyValueMap.put("airInletPressureStackCurrentImageWidth", 300);
        keyValueMap.put("airInletPressureStackCurrentImageHeight", 500);

        keyValueMap.put("image6.jpeg", createImage("6"));
        keyValueMap.put("airMassFlowStackCurrentImageWidth", 300);
        keyValueMap.put("airMassFlowStackCurrentImageHeight", 500);

        keyValueMap.put("image7.jpeg", createImage("7"));
        keyValueMap.put("anodeDpWithoutPurgeStackCurrentImageWidth", 300);
        keyValueMap.put("anodeDpWithoutPurgeStackCurrentImageHeight", 500);

        keyValueMap.put("image8.jpeg", createImage("8"));
        keyValueMap.put("anodeDpWithPurgeStackCurrentImageWidth", 300);
        keyValueMap.put("anodeDpWithPurgeStackCurrentImageHeight", 500);

        keyValueMap.put("image9.jpeg", createImage("9"));
        keyValueMap.put("coolantInletTemperatureStackCurrentImageWidth", 300);
        keyValueMap.put("coolantInletTemperatureStackCurrentImageHeight", 500);

        keyValueMap.put("image10.jpeg", createImage("10"));
        keyValueMap.put("coolantDtStackCurrentImageWidth", 300);
        keyValueMap.put("coolantDtStackCurrentImageHeight", 500);

        keyValueMap.put("image11.jpeg", createImage("11"));
        keyValueMap.put("hrbSpeedStackCurrentImageWidth", 300);
        keyValueMap.put("hrbSpeedStackCurrentImageHeight", 500);

        keyValueMap.put("image12.jpeg", createImage("12"));
        keyValueMap.put("wcpSpeedStackCurrentImageWidth", 300);
        keyValueMap.put("wcpSpeedStackCurrentImageHeight", 500);

        keyValueMap.put("image13.jpeg", createImage("13"));
        keyValueMap.put("acpSpeedStackCurrentImageWidth", 300);
        keyValueMap.put("acpSpeedStackCurrentImageHeight", 500);
//        exportPpt(new File("C:/Users/熊浪/Desktop/20210611/1.ppt"), keyValueMap);
        //设置模板格式和路径
        //PptUtil.exportPPT("D:/IDEAWORKSPACES/master_data_service/src/main/resources/bin", "IDURABILITY.xml", "C:/Users/熊浪/Desktop/20210830/test.xml", keyValueMap);
        PptUtil.exportPPT("D:/IDEAWORKSPACES/master_data_service/src/main/resources/bin", "IDURABILITY.pptx", "C:/Users/熊浪/Desktop/20210830/test.pptx", keyValueMap);
    }


    private static ImageEntity createImage(String testStr) {
    
    
        DmasChartData dmasChartData = new DmasChartData();
        ChartStyleValue tempChartStyleValue = new ChartStyleValue();
        tempChartStyleValue.setEllipseIndex(2);
        dmasChartData.addXMinValue(0D).addXMaxValue(100D).addYMinValue(0D).addYMaxValue(100D).addXNumberTick(10D).addYNumberTick(10D)
                .putNameChartStyleValue("123", tempChartStyleValue);
        dmasChartData.addXyValue("123", 0, "10", "20", null, null);
        JFreeChart chart = ChartUtils.xYLineChart("测试【" + testStr + "】下", "时间", "数据", null);
        AtomicInteger atomicInteger = new AtomicInteger(0);
        dmasChartData.getDotLineNameChartStyleValueMap().forEach((xyItemRenderer, nameChartStyleValueMap) -> {
    
    
            int index = atomicInteger.getAndAdd(1);
            XYDataset xyDataset = null;
            if (dmasChartData.isTime()) {
    
    
                xyDataset = new TimeSeriesCollection();
                DateAxis dateAxis = new DateAxis();
                dateAxis.setDateFormatOverride(new SimpleDateFormat(dmasChartData.getPattern()));
                chart.getXYPlot().setDomainAxis(index, dateAxis);
            } else {
    
    
                xyDataset = new XYSeriesCollection();
            }
            XYDataset finalXyDataset = xyDataset;
            nameChartStyleValueMap.forEach((name, chartStyleValue) -> {
    
    
                chartStyleValue.buildXYItemRenderer(xyItemRenderer, finalXyDataset, name);
            });
            chart.getXYPlot().setRenderer(index, xyItemRenderer);
            chart.getXYPlot().setDataset(index, xyDataset);
            /**
             * X轴取值范围
             */
            ValueAxis domainAxis = chart.getXYPlot().getDomainAxis(index);
            if (domainAxis != null && domainAxis instanceof NumberAxis) {
    
    
                NumberAxis xNumberAxis = (NumberAxis) domainAxis;
                if (dmasChartData.getXMinValue() != null && dmasChartData.getXMaxValue() != null) {
    
    
                    xNumberAxis.setRange(dmasChartData.getXMinValue(), dmasChartData.getXMaxValue());
                    xNumberAxis.setTickUnit(new NumberTickUnit(dmasChartData.getXNumberTick()));
                    xNumberAxis.setVerticalTickLabels(Boolean.TRUE);
                }
            }
            /**
             * Y轴取值范围
             */
            ValueAxis rangeAxis = chart.getXYPlot().getRangeAxis(index);
            if (rangeAxis != null && rangeAxis instanceof NumberAxis) {
    
    
                NumberAxis yNumberAxis = (NumberAxis) rangeAxis;
                if (dmasChartData.getYMinValue() != null && dmasChartData.getYMaxValue() != null) {
    
    
                    yNumberAxis.setRange(dmasChartData.getYMinValue(), dmasChartData.getYMaxValue());
                    yNumberAxis.setTickUnit(new NumberTickUnit(dmasChartData.getYNumberTick()));
                    yNumberAxis.setVerticalTickLabels(Boolean.TRUE);
                }
            }
        });
        chart.getXYPlot().setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
        chart.getXYPlot().setSeriesRenderingOrder(SeriesRenderingOrder.FORWARD);
        return ChartUtils.creatImag(chart, "123Jfree.jpeg", 500, 500);
    }
}


在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/xionglangs/article/details/120365758