Java基於POI對PPT的基本操作

Java基於POI對PPT的基本操作

         在Java中對PPT文件進行操作的話,我使用的是Apache的開源項目POI。該項目的功能主要是使用Java開發或生成微軟辦公文件,比如:Word、Excel、PPT、Visio等。其中實現對PPT文件進行操作的類包主要是HSLF(.ppt)和XSLF(.pptx),在本文中,會以XSLF爲主。

一、創建PPT文件,並生成空白幻燈片

package com.jointstarc.test;

 

import java.io.FileOutputStream;

import java.io.IOException;

 

import org.apache.poi.xslf.usermodel.XMLSlideShow;

import org.apache.poi.xslf.usermodel.XSLFSlide;

 

public class Demo1 {

    public static void main(String[] args) {

       // 創建一個空白PPT

       XMLSlideShow ppt = new XMLSlideShow();

       // 在空白的PPT中創建一個空白的幻燈片

       XSLFSlide slide = ppt.createSlide();

       try {

           // 對新建的PPT保存到硬盤裏

           ppt.write(new FileOutputStream("D://test3.pptx"));

       } catch (Exception e) {

           e.printStackTrace();

       } finally {

           if (ppt != null) {

              try {

                  // 保存完之後要對PPT進行關閉操作

                  ppt.close();

              } catch (IOException e) {

                  e.printStackTrace();

              }

           }

       }

    }

}

二、在空白幻燈片中添加內容

2.1、添加文本框和超鏈接

/*

        * 在空幻燈片中插入一個文本框,然後在文本框中寫入文字,

        * 並給文字添加一個超鏈接

        */

       // 在幻燈片中插入一個文本框

       XSLFTextShape ts = slide.createTextBox();

       // 設置文本框的位置和文本框大小

       ts.setAnchor(new Rectangle(150, 150, 200, 50));

       // 設置文本框裏面的文字

       XSLFTextRun tr = ts.addNewTextParagraph().addNewTextRun();

       tr.setText("測試一下");

       // 給文本添加顏色

       tr.setFontColor(Color.RED);

       // 給文本添加超鏈接

       XSLFHyperlink link = tr.createHyperlink();

        link.setAddress("http://www.baidu.com");

2.2、添加表格

/*

         * 在幻燈片中添加表格

         */

        // 在幻燈片中插入一個表格

        XSLFTable table = slide1.createTable();

        // 設置表格的位置和表格大小

        table.setAnchor(new Rectangle(50, 100, 100, 100));

        for (int i = 0; i < 5; i++) {

            // 在表格中添加一行

            XSLFTableRow row = table.addRow();

            for (int j = 0; j < 5; j++) {

               // 在行中添加一個單元格

               XSLFTableCell cell = row.addCell();

               // 設置單元格中的內容和樣式

               XSLFTextParagraph p = cell.addNewTextParagraph();

               p.setTextAlign(TextAlign.CENTER);

               XSLFTextRun tr1 = p.addNewTextRun();

               tr1.setFontColor(Color.RED);

               tr1.setText("測試" + i + j);

               // 設置單元格邊框的粗細

               cell.setBorderWidth(BorderEdge.bottom, 2.0);

                cell.setBorderWidth(BorderEdge.left, 2.0);

                cell.setBorderWidth(BorderEdge.right, 2.0);

                cell.setBorderWidth(BorderEdge.top, 2.0);

                // 設置單元格邊框的顏色

                cell.setBorderColor(BorderEdge.bottom, Color.black);

                cell.setBorderColor(BorderEdge.left, Color.black);

                cell.setBorderColor(BorderEdge.right, Color.black);

                cell.setBorderColor(BorderEdge.top, Color.black);

           }

        }

2.3、添加圖片

/*

         * 在幻燈片中插入一張圖片

         */

        // 圖片文件

        File image = new File("D://111.jpg");

        // 圖片文件輸入流

       FileInputStream imageFis = new FileInputStream(image);

       // 獲取圖片大小

       int len = (int) image.length();

       // 創建一個字節數組,數組大小與圖片文件大小一致

       byte[] imageData = new byte[len];

       // 將圖片數據讀進字節數組中

       imageFis.read(imageData);

       // 將圖片添加到PPT

       XSLFPictureData pd = ppt.addPicture(imageData, PictureData.PictureType.JPEG);

       // 將圖片放到指定的幻燈片中

        XSLFPictureShape pic = slide2.createPicture(pd);

      // 設置圖片框的放置的位置和大小

        pic.setAnchor(new Rectangle(50, 100, 200, 200));

三、讀取現有的PPT文件,並在已有的幻燈片後添加幻燈片

package com.jointstarc.test;

 

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

 

import org.apache.poi.xslf.usermodel.XMLSlideShow;

import org.apache.poi.xslf.usermodel.XSLFSlide;

 

public class Demo2 {

    public static void main(String[] args) {

       XMLSlideShow ppt = null;

       try {

           // 通過輸入流讀取一個現有的PPT文件,生成PPT

           ppt = new XMLSlideShow(new FileInputStream("D://test.pptx"));

           // 在現有的PPT文件後面新建一個空白幻燈片

           XSLFSlide slide = ppt.createSlide();

           // 將修改後的PPT文件回寫到硬盤

           ppt.write(new FileOutputStream("D://test3.pptx"));

       } catch (Exception e) {

           e.printStackTrace();

       } finally {

           if (ppt != null) {

              try {

                  // 保存完之後要對PPT進行關閉操作

                  ppt.close();

              } catch (IOException e) {

                  e.printStackTrace();

              }

           }

       }

    }

}

四、讀取現有的PPT內容,並進行修改

4.1、獲取PPT的所有文本框裏的文字,並進行更改

/*

 * 獲取PPT的所有文本框裏的文字,並進行更改

 */

// 獲取PPT中的所有幻燈片

List<XSLFSlide> slides = ppt.getSlides();

// 遍歷幻燈片

for (XSLFSlide slide : slides) {

    // 獲取幻燈片中的所有圖形(文本框、表格、圖形...

    List<XSLFShape> shapes = slide.getShapes();

    // 遍歷圖形

    for (XSLFShape shape : shapes) {

        // 判斷該圖形類是否是文本框類

        if (shape instanceof XSLFTextShape) {

           // 將圖像類強制裝換成文本框類

           XSLFTextShape ts = (XSLFTextShape) shape;

           // 獲取文本框內的文字

           String str = ts.getText();

           System.out.println(str);

          

           // 若想對文本框內的文字進行更改,還需要進行如下步驟

           List<XSLFTextParagraph> textParagraphs = ts.getTextParagraphs();

           for (XSLFTextParagraph tp : textParagraphs) {

              List<XSLFTextRun> textRuns = tp.getTextRuns();

              for (XSLFTextRun r : textRuns) {

                  if ("201809".equals(r.getRawText())) {

                     // 對匹配到的字符串進行更改

                     r.setText("2018-09");

                     // 設置字體顏色

                     r.setFontColor(Color.RED);

                  }

              }

           }

         }

    }

}

4.2、獲取PPT的所有表格裏的文字,並進行更改

/*

 * 獲取PPT的所有表格裏的文字,並進行更改

 */

// 獲取PPT中的所有幻燈片

List<XSLFSlide> slides = ppt.getSlides();

for (XSLFSlide slide : slides) {

    // 獲取幻燈片中的所有圖形(文本框、表格、圖形...

    List<XSLFShape> shapes = slide.getShapes();

    for (XSLFShape shape : shapes) {

       // 判斷該圖形類是否是表格類

       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) {

                  // 獲取單元格內的文字

                  String str = tc.getText();

                  // 若想對錶格內的文字進行更改,還需要進行如下步驟

                  List<XSLFTextParagraph> textParagraphs = tc.getTextParagraphs();

                  for (XSLFTextParagraph tp : textParagraphs) {

                     List<XSLFTextRun> textRuns = tp.getTextRuns();

                     for (XSLFTextRun r : textRuns) {

                         if ("風險指標".equals(r.getRawText())) {

                            // 對匹配到的字符串進行更改

                            r.setText("測試修改文字");

                            // 設置字體顏色

                            r.setFontColor(Color.RED);

                         }

                     }

                  }

              }

           }

       }

    }

}

4.3、獲取PPT的所有圖片,並進行更改

/*

 * 獲取PPT的所有圖片,並進行更改

 */

// 獲取PPT中的所有幻燈片

List<XSLFSlide> slides = ppt.getSlides();

for (XSLFSlide slide : slides) {

    // 獲取幻燈片中的所有圖形(文本框、表格、圖形...

    List<XSLFShape> shapes = slide.getShapes();

    for (XSLFShape shape : shapes) {

        // 判斷該圖形類是否是圖片框類

        if (shape instanceof XSLFPictureShape) {

           /*

            * 獲取圖片數據

            */

           // 將圖像類強制裝換成圖片框類

           XSLFPictureShape ps = (XSLFPictureShape) shape;

           // 獲取圖片的字節碼數據(可以利用輸出流將該圖片保存到硬盤裏)

           byte [] pictureData = ps.getPictureData().getData();

           /*

            * 更改圖片

            */

           // 圖片文件

            File image = new File("D://222.jpg");

            // 圖片文件輸入流

           FileInputStream imageFis = new FileInputStream(image);

           // 獲取圖片大小

           int len = (int) image.length();

           // 創建一個字節數組,數組大小與圖片文件大小一致

           byte[] imageData = new byte[len];

          

           if (imageFis.read(imageData) != -1) {

               // 更換圖片必須圖片設置索引,要不不生效

                ps.getPictureData().setIndex(1);

                ps.getPictureData().setData(imageData);

           }

           // 關閉輸入流

           imageFis.close();

         }

    }

}

 

 若轉裝載,請標明來源,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章