使用org.apache.poi導出ppt學習分享(一)


第一次使用org.apache.poi做ppt導出,隨手記錄下。

依賴導入:

使用版本: org.apache.poi:poi-ooxml:5.2.0

 

https://search.maven.org/artifact/org.apache.poi/poi-ooxml/5.2.0/jar

打開地址  在左上角選取版本,在右側復制依賴引入。  我這里實用的是Gradle

 

 

 實際使用中 除了poi_ooxml外,還要引入幾個依賴,否則會導致編譯報錯,xxxx函數找不到。共需引入4個依賴包,如下:

    //poi-ooxml
    implementation 'org.apache.poi:poi-ooxml:5.2.0'
    implementation 'org.apache.poi:poi:5.2.0'
    implementation 'commons-io:commons-io:2.11.0'
    implementation 'org.apache.logging.log4j:log4j-api:2.17.1'

使用:

XMLSlideShow讀取或者新建ppt:

這個類表示ppt本身,提供了多個構造函數,這里我們使用帶參數的構造函數來讀取ppt模板:

//加載模板
File file = new File(“D:\\opencv\\template\\template.pptx”);
FileInputStream fileInputStream = new FileInputStream(file);
//加載ppt演示文稿模板
XMLSlideShow ppt = new XMLSlideShow(fileInputStream);

這個類也提供了無參構造,用於新建一個全新的ppt

XSLFSlide讀取或新建幻燈片:

這個類表示幻燈片,每一個對象是一張幻燈片。由於我們使用的是准備好的模板,所以通過XMLSlideShow對象來獲取模板中的幻燈片列表

//讀取ppt中的幻燈片
List<XSLFSlide> xslfSlideList = ppt.getSlides();

XSLFSlide frontPage = xslfSlideList.get(0);

 

使用XSLFTextBox添加文字:

用於添加文字:

//向幻燈片中插入文字
XSLFTextBox xslfTextBox = frontPage.createTextBox(); xslfTextBox.appendText(“此處填寫文字內容”, true);
//文字位置(文字框左上角坐標 450, 74 。 文字框寬高 280, 43) Rectangle2D rectText
= new Rectangle2D.Double(450, 74, 280, 43); xslfTextBox.setAnchor(rectText);

 使用XSLFPictureData向添加圖片:

用於插入圖片:

//獲取圖片文件
File image=new File("E:\\IMG0002_1628151287000_4a82632842924f3bbaf72bd64d744464.JPG");
byte[] picture = IOUtils.toByteArray(new FileInputStream(image));
//將圖片加入ppt演示文稿
XSLFPictureData pictureData = ppt.addPicture(picture, PictureData.PictureType.JPEG);
//把圖片插入幻燈片並設置圖片位置和大小 XSLFPictureShape pic
= frontPage.createPicture(pictureData);
Rectangle2D rectImage = new Rectangle2D.Double(20, 20, 200, 200)
pic.setAnchor(rectImage);

 輸出ppt文件:

//輸出新的演示文稿
File outFile=new File("D:\\opencv\\template\\addingimage.pptx");
FileOutputStream out = new FileOutputStream(outFile);
ppt.write(out);
out.close();

 

PS:  還有其他諸如占位符替換等操作,有時間的話后面會再整理一篇文章。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM