欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

利用Apache POI操作ppt模板

程序员文章站 2022-07-13 12:26:24
...

利用Apache POI操作ppt模板

实现的是读取ppt模板,修改动态数据,输出新ppt文件

构建的时maven项目所依赖如下

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

<!--        依赖引入-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.19</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-spring-boot-starter</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.2.0</version>
        </dependency>

<!--        导出ppt的poi所需依赖-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.1</version>
        </dependency>


        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
            <scope>compile</scope>
        </dependency>


    </dependencies>

阶段一

  • 能修改模板中的数据,但是无法保留样式
  • 注,模板中需要修改的数据 改为 {xxx} 的形式,不可重名,且目前测试不能用汉字。我多用数字代替
        //这种方式改变模板数据,无法保留原有样式
        //读取原始模板ppt数据
        String modelPath = "D://统计结果导出.pptx";
        XMLSlideShow slideShow = new XMLSlideShow(new FileInputStream(modelPath));

        List<XSLFSlide> slides = slideShow.getSlides();
        for (XSLFSlide slide : slides) {
            List<XSLFShape> shapes = slide.getShapes();
            for (XSLFShape shape : shapes) {
                if (shape instanceof XSLFAutoShape) {
                    XSLFAutoShape autoShape = (XSLFAutoShape) shape;
                    String text = autoShape.getText();
                    if (text.contains("{test}")) {
                        XSLFTextRun textRun = autoShape.setText(text.replace("{test}", "改变成功"));
                        textRun.setFontColor(Color.black);
                        textRun.setFontFamily("微软雅黑");
                        textRun.setFontSize(14.0);
                    }
                }
            }
        }

        slideShow.write(new FileOutputStream("D://统计结果导出test.pptx"));

阶段二

  • 利用paragraphs,可以保留原有样式
  List<Stat> stats = this.statService.selectAll();
    stats.forEach(stat -> {
        String modelPath = "D://模板.pptx";
        XMLSlideShow slideShow = null;
        try {
            slideShow = new XMLSlideShow(new FileInputStream(modelPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<XSLFSlide> slides = slideShow.getSlides();
        for (XSLFSlide slide : slides){
            List<XSLFShape> shapes = slide.getShapes();
            for (XSLFShape shape : shapes){

//                修改文本数据利用textshape
                if (shape instanceof TextShape){
                    List<XSLFTextParagraph> textParagraphs = ((TextShape) shape).getTextParagraphs();
                    if (textParagraphs == null || textParagraphs.size() == 0){
                        continue;
                    }
                    for (XSLFTextParagraph textParagraph : textParagraphs){
                        if (textParagraph == null){
                            continue;
                        }
                         List<XSLFTextRun> textRuns = textParagraph.getTextRuns();
                        if (textRuns == null){
                            continue;
                        }
                        for (XSLFTextRun textRun : textRuns){
                            textRun.setText(textRun.getRawText().replace("{1}",stat.getRefPre()));
                        }
                    }
                }
                   try {
            slideShow.write(new FileOutputStream("D://输出新文档test.pptx"));
        } catch (IOException e) {
            e.printStackTrace();
        }
  • shape instanceof TextShape 只能操作文本数据

阶段三

修改ppt文档中的表格数据,利用 shape instanceof XSLFTable

 List<Stat> stats = this.statService.selectAll();
    stats.forEach(stat -> {
        String modelPath = "D://模板.pptx";
        XMLSlideShow slideShow = null;
        try {
            slideShow = new XMLSlideShow(new FileInputStream(modelPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<XSLFSlide> slides = slideShow.getSlides();
        for (XSLFSlide slide : slides){
            List<XSLFShape> shapes = slide.getShapes();
            for (XSLFShape shape : shapes){
                //                修改表格数据 利用xslfTable
               else if (shape instanceof XSLFTable){
//                    XSLFTableCell cell = ((XSLFTable) shape).getCell(2, 2);
                     int rows = ((XSLFTable) shape).getNumberOfRows();
                     int columns = ((XSLFTable) shape).getNumberOfColumns();
                     for (int i = 0; i< rows; i++){
                         for (int j = 0;j < columns;j++){
                             String text = ((XSLFTable) shape).getCell(i, j).getText();
                             if (StringUtils.isNotBlank(text) && StringUtils.isNotEmpty(text)){
//                                 ((XSLFTable) shape).getCell(i,j).setText();
                                 ((XSLFTable) shape).getCell(i,j).setText(((XSLFTable) shape).getCell(i,j).getText().replace("{call}",stat.getCall()));
                                 ((XSLFTable) shape).getCell(i,j).setText(((XSLFTable) shape).getCell(i,j).getText().replace("{connect}",stat.getConnect()));
                                 ((XSLFTable) shape).getCell(i,j).setText(((XSLFTable) shape).getCell(i,j).getText().replace("{noneCollect}",stat.getNoneCollect()));
                                 ((XSLFTable) shape).getCell(i,j).setText(((XSLFTable) shape).getCell(i,j).getText().replace("{ref}",stat.getRef()));
                                 ((XSLFTable) shape).getCell(i,j).setText(((XSLFTable) shape).getCell(i,j).getText().replace("{connectPre}",stat.getConnectPre()));
                                 ((XSLFTable) shape).getCell(i,j).setText(((XSLFTable) shape).getCell(i,j).getText().replace("{refPre}",stat.getRefPre()));
                                 ((XSLFTable) shape).getCell(i,j).setText(((XSLFTable) shape).getCell(i,j).getText().replace("{usefulCollect}",stat.getUsefulCollect()));
                             }
                         }
                     }

                 }
            }
        }

        try {
            slideShow.write(new FileOutputStream("D://输出新文件模板test.pptx"));
        } catch (IOException e) {
            e.printStackTrace();
        }

阶段四

自己手动创建一个带表格的ppt

       String[] strings1 = new String[9];

        strings1= this.statService.selectAll();
        System.out.println(strings1[3]);
        System.out.println(strings1[5]);
        System.out.println("-=-=-=-=-=-=-=-=-=");

        String[] strings = new String[3];
        strings[0] = "hello";
        strings[1] = "hell";
        strings[2] = "hello13";
        *//** 加载PPT **//*
        XMLSlideShow ppt = new XMLSlideShow();

        *//** 创建一个slide,理解为PPT里的每一页 **//*
        XSLFSlide slide = ppt.createSlide();
        *//** 获得slideMasters**//*
        List<XSLFSlideMaster> slideMasters = ppt.getSlideMasters();
        *//** 创建表格**//*
        XSLFTable table = slide.createTable();
        *//** 设置表格 x ,y ,width,height **//*
        Rectangle2D rectangle2D = new Rectangle2D.Double(20, 90, 2200, 500);


        stats.forEach(stat -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("有效采集", stat.getUsefulCollect());
            map.put("接通", stat.getConnect());
            map.put("拒接", stat.getRef());
            map.put("未接通", stat.getNoneCollect());
            map.put("呼叫", stat.getCall());
            map.put("接通率", stat.getConnectPre());
            map.put("有效采集率接通", stat.getUsefulConnectCollect());
            map.put("有效采集率呼叫", stat.getUsefulCallCollect());
            map.put("拒接率", stat.getRefPre());


            System.out.println("=================");
            System.out.println(map);
            System.out.println("=================");
            Set<Map.Entry<String, Object>> set = map.entrySet();
            System.out.println(set);
            System.out.println("=================");
            Set<String> setkey = map.keySet();
            System.out.println(setkey);
            System.out.println("=================");

            //迭代输出map中的kv
            for (String key : map.keySet()) {
                Object o = map.get(key);
                System.out.println(key + ":" + o);

                *//** 生成第一行 **//*
                XSLFTableRow firstRow = table.addRow();

                XSLFTableCell cell = firstRow.addCell();
                cell.setBorderColor(TableCell.BorderEdge.left, new Color(10, 100, 120));
                cell.setBorderColor(TableCell.BorderEdge.right, new Color(10, 100, 120));
                cell.setBorderColor(TableCell.BorderEdge.bottom, new Color(10, 100, 120));
                cell.setBorderColor(TableCell.BorderEdge.top, new Color(10, 100, 120));

                cell.setBorderWidth(TableCell.BorderEdge.left, 3);
                cell.setBorderWidth(TableCell.BorderEdge.right, 3);
                cell.setBorderWidth(TableCell.BorderEdge.top, 3);
                cell.setBorderWidth(TableCell.BorderEdge.bottom, 3);

                cell.setText(key + ":" + o);
            }


        });*/

        /* *//** 生成第一个单元格**//*
        XSLFTableCell firstCell =  firstRow.addCell();

        *//** 设置单元格的边框颜色 **//*
        firstCell.setBorderColor(TableCell.BorderEdge.left,new Color(10,100,120));
        firstCell.setBorderColor(TableCell.BorderEdge.right,new Color(10,100,120));
        firstCell.setBorderColor(TableCell.BorderEdge.top,new Color(10,100,120));
        firstCell.setBorderColor(TableCell.BorderEdge.bottom,new Color(10,100,120));

        *//** 设置单元格边框 **//*
        firstCell.setBorderWidth(TableCell.BorderEdge.left,3);
        firstCell.setBorderWidth(TableCell.BorderEdge.right,3);
        firstCell.setBorderWidth(TableCell.BorderEdge.top,3);
        firstCell.setBorderWidth(TableCell.BorderEdge.bottom,3);
        *//** 设置文本 **//*
        users.forEach(user -> {
            String name = user.getName();
            System.out.println("=============");
            firstCell.setText(name);
        });


        *//** 设置单元格的边框宽度 **//*
//        创建第一行第二个单元格
        XSLFTableCell secondCell =  firstRow.addCell();
        secondCell.setText("sfdsf");
        *//** 设置单元格的边框颜色 **//*
        secondCell.setBorderColor(TableCell.BorderEdge.bottom,new Color(10,100,120));
        secondCell.setBorderColor(TableCell.BorderEdge.right,new Color(10,100,120));
        secondCell.setBorderColor(TableCell.BorderEdge.left,new Color(10,100,120));
        secondCell.setBorderColor(TableCell.BorderEdge.top,new Color(10,100,120));

        *//** 设置单元格边框 **//*
        secondCell.setBorderWidth(TableCell.BorderEdge.left,3);
        secondCell.setBorderWidth(TableCell.BorderEdge.right,3);
        secondCell.setBorderWidth(TableCell.BorderEdge.top,3);
        secondCell.setBorderWidth(TableCell.BorderEdge.bottom,3);

      table.setAnchor(rectangle2D);

        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("统计结果导出.pptx", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();

        /** 文件路径 **/
        String filePath = "D://统计结果导出.pptx";
        /** 输出文件 **/
       ppt.write(outputStream);
        outputStream.close();
        ppt.close();
        ppt.write(new FileOutputStream(filePath));
相关标签: poi ppt