Apache POI PPT - 演示
一般来说,我们使用MS-PowerPoint来创建演示文稿。 现在让我们看看如何使用Java创建演示文稿。 完成本章后,您将能够创建新的MS-PowerPoint演示文稿,并使用您的Java程序打开现有的PPT。
创建空的演示文稿
要创建空的演示文稿,您必须实例化 org.poi.xslf.usermodel 包的 XMLSlideShow 类:
XMLSlideShow ppt = new XMLSlideShow();
使用 FileOutputStream 类将更改保存到PPT文档:
File file=new File("C://POIPPT//Examples//example1.pptx");
FileOutputStream out = new FileOutputStream(file);
ppt.write(out);
以下是创建空白MS-PowerPoint演示文稿的完整程序。
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
public class CreatePresentation {
public static void main(String args[]) throws IOException{
//creating a new empty slide show
XMLSlideShow ppt = new XMLSlideShow();
//creating an FileOutputStream object
File file =new File("example1.pptx");
FileOutputStream out = new FileOutputStream(file);
//saving the changes to a file
ppt.write(out);
System.out.println("Presentation created successfully");
out.close()
}
}
将上面的Java代码保存为 CreatePresentation.java ,然后从命令提示符处编译并执行它,如下所示:
$javac CreatePresentation.java $java CreatePresentation
如果您的系统环境配置有POI库,它将编译并执行,以在当前目录中生成名为 example1.pptx 的空白PPT文件,并在命令提示符下显示以下输出:
Presentation created successfully
空白PowerPoint文档显示如下:

编辑现有演示文稿
要打开现有的演示文稿,请实例化 XMLSlideShow 类,并将要编辑的文件的 FileInputStream 对象作为 XMLSlideShow 构造函数的参数传递 。
File file=new File(“C://POIPPT//Examples//example1.pptx"); FileInputstream inputstream =new FileInputStream(file); XMLSlideShow ppt = new XMLSlideShow(inputstream);
您可以使用 org.poi.xslf.usermodel 包中的XMLSlideShow类的 createSlide()方法将幻灯片添加到演示文稿。
XSLFSlide slide1= ppt.createSlide();
下面给出了打开和添加幻灯片到现有PPT的完整程序:
import java.io.File;
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 EditPresentation {
public static void main(String ar[]) throws IOException{
//opening an existing slide show
File file = new File("example1.pptx");
FileInputStream inputstream=new FileInputStream(file);
XMLSlideShow ppt = new XMLSlideShow(inputstream);
//adding slides to the slodeshow
XSLFSlide slide1 = ppt.createSlide();
XSLFSlide slide2 = ppt.createSlide();
//saving the changes
FileOutputStream out = new FileOutputStream(file);
ppt.write(out);
System.out.println("Presentation edited successfully");
out.close();
}
}
将上述Java代码另存为 EditPresentation.java ,然后从命令提示符处编译并执行,如下所示:
$javac EditPresentation.java $java EditPresentation
它将编译并执行以生成以下输出:
slides successfully added
带有新添加的幻灯片的输出PPT文档如下所示:

将幻灯片添加到PPT后,您可以在幻灯片上添加,执行,读取和写入操作。

免费 AI IDE


更多建议: