Creating a MS PowerPoint Presentation in Java – 在Java中创建一个MS PowerPoint演示文稿

最后修改: 2017年 12月 5日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this article, we’ll see how we can create a presentation using Apache POI.

在这篇文章中,我们将看到如何使用Apache POI创建一个演示文稿。

This library gives us a possibility to create PowerPoint presentations, read existing ones, and to alter their content.

这个库让我们有可能创建PowerPoint演示文稿,阅读现有的演示文稿,并改变其内容。

2. Maven Dependencies

2.Maven的依赖性

To begin, we’ll need to add the following dependencies into our pom.xml:

首先,我们需要在我们的pom.xml中添加以下依赖项。

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>

The latest version of both libraries can be downloaded from Maven Central.

这两个库的最新版本可以从Maven中心下载。

3. Apache POI

3.Apache POI

The Apache POI library supports both .ppt and .pptx files, and it provides the HSLF implementation for the Powerpoint ’97(-2007) file format and the XSLF for the PowerPoint 2007 OOXML file format.

Apache POI库支持.ppt.pptx文件,它为Powerpoint ’97(-2007)文件格式提供HSLF实现,为PowerPoint 2007 OOXML文件格式提供XSLF。

Since a common interface doesn’t exist for both implementations, we have to remember to use the XMLSlideShow, XSLFSlide and XSLFTextShape classes when working with the newer .pptx file format.

由于两种实现都不存在一个共同的接口,我们必须记得在处理较新的.pptx文件格式时使用XMLSlideShowXSLFSlideXSLFTextShape类。

And, when it’s required to work with the older .ppt format, use the HSLFSlideShow, HSLFSlide and HSLFTextParagraph classes.

而且,当需要使用旧的.ppt格式时,使用HSLFSlideShowHSLFSlideHSLFTextParagraph类。

We’ll use the new .pptx file format in our examples, and the first thing we have to do is create a new presentation, add a slide to it (maybe using a predefined layout) and save it.

在我们的例子中,我们将使用新的.pptx文件格式,我们要做的第一件事是创建一个新的演示文稿,为其添加一张幻灯片(也许使用预定义的布局)并保存它。

Once these operations are clear, we can then start working with images, text, and tables.

一旦这些操作清楚了,我们就可以开始处理图像、文本和表格。

3.1. Create a New Presentation

3.1.创建一个新的演示文稿

Let’s first create the new presentation:

让我们首先创建新的演示文稿。

XMLSlideShow ppt = new XMLSlideShow();
ppt.createSlide();

3.2. Add a New Slide

3.2.添加新幻灯片

When adding a new slide to a presentation, we can also choose to create it from a predefined layout. To achieve this, we first have to retrieve the XSLFSlideMaster that holds layouts (the first one is the default master):

在向演示文稿中添加新的幻灯片时,我们也可以选择从一个预定义的布局来创建它。为了实现这一点,我们首先要检索持有布局的XSLFSlideMaster(第一个是默认主控)。

XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0);

Now, we can retrieve the XSLFSlideLayout and use it when creating the new slide:

现在,我们可以检索到XSLFSlideLayout并在创建新幻灯片时使用它。

XSLFSlideLayout layout 
  = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
XSLFSlide slide = ppt.createSlide(layout);

Let’s see how to fill placeholders inside a template:

让我们看看如何在一个模板内填充占位符。

XSLFTextShape titleShape = slide.getPlaceholder(0);
XSLFTextShape contentShape = slide.getPlaceholder(1);

Remember that each template has its placeholders, instances of the XSLFAutoShape subclass, which could differ in number from one template to another.

请记住,每个模板都有它的占位符,即XSLFAutoShape子类的实例,每个模板的数量可能不同。

Let’s see how we can quickly retrieve all placeholders from a slide:

让我们看看如何快速检索幻灯片中的所有占位符。

for (XSLFShape shape : slide.getShapes()) {
    if (shape instanceof XSLFAutoShape) {
        // this is a template placeholder
    }
}

3.3. Saving a Presentation

3.3.保存演示文稿

Once we’ve created the slideshow, the next step is to save it:

一旦我们创建了幻灯片,下一步就是保存它。

FileOutputStream out = new FileOutputStream("powerpoint.pptx");
ppt.write(out);
out.close();

4. Working With Objects

4.使用对象

Now that we saw how to create a new presentation, add a slide to it (using or not a predefined template) and save it, we can start adding text, images, links, and tables.

现在我们看到了如何创建一个新的演示文稿,向其添加幻灯片(使用或不使用预定义的模板)并保存它,我们可以开始添加文本、图像、链接和表格。

Let’s start with the text.

让我们从文本开始。

4.1. Text

4.1.文本

When working with text inside a presentation, as in MS PowerPoint, we have to create the text box inside a slide, add a paragraph and then add the text to the paragraph:

在演示文稿中处理文本时,如在MS PowerPoint中,我们必须在幻灯片中创建文本框,添加一个段落,然后将文本添加到该段落。

XSLFTextBox shape = slide.createTextBox();
XSLFTextParagraph p = shape.addNewTextParagraph();
XSLFTextRun r = p.addNewTextRun();
r.setText("Baeldung");
r.setFontColor(Color.green);
r.setFontSize(24.);

When configuring the XSLFTextRun, it’s possible to customize its style by picking the font family and if the text should be in bold, italic or underlined.

在配置XSLFTextRun时,可以通过选择字体家族以及文本是否应使用粗体、斜体或下划线来定制其风格。

4.2. Hyperlinks

4.2.超链接

When adding text to a presentation, sometimes it can be useful to add hyperlinks.

在向演示文稿中添加文本时,有时添加超链接会很有用。

Once we have created the XSLFTextRun object, we can now add a link:

一旦我们创建了XSLFTextRun对象,我们现在可以添加一个链接。

XSLFHyperlink link = r.createHyperlink();
link.setAddress("http://www.baeldung.com");

4.3. Images

4.3.图像

We can add images, as well:

我们也可以添加图片。

byte[] pictureData = IOUtils.toByteArray(
  new FileInputStream("logo-leaf.png"));

XSLFPictureData pd
  = ppt.addPicture(pictureData, PictureData.PictureType.PNG);
XSLFPictureShape picture = slide.createPicture(pd);

However, without a proper configuration, the image will be placed in the top left corner of the slide. To place it properly, we have to configure its anchor point:

然而,如果没有适当的配置,图片将被放置在幻灯片的左上角。为了正确放置它,我们必须配置它的锚点。

picture.setAnchor(new Rectangle(320, 230, 100, 92));

The XSLFPictureShape accepts a Rectangle as an anchor point, which allows us to configure the x/y coordinates with the first two parameters, and the width/height of the image with the last two.

XSLFPictureShape接受一个Rectangle作为锚点,这使得我们可以用前两个参数配置x/y坐标,用后两个参数配置图像的宽度/高度。

4.4. Lists

4.4.列表

Text, inside of a presentation, is often represented in the form of a list, numbered or not.

在演示文稿中,文本通常以列表的形式表示,无论是否有编号。

Let’s now define a list of bullet points:

现在我们来定义一个要点清单。

XSLFTextShape content = slide.getPlaceholder(1);
XSLFTextParagraph p1 = content.addNewTextParagraph();
p1.setIndentLevel(0);
p1.setBullet(true);
r1 = p1.addNewTextRun();
r1.setText("Bullet");

Similarly, we can define a numbered list:

同样地,我们可以定义一个有编号的列表。

XSLFTextParagraph p2 = content.addNewTextParagraph();
p2.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);
p2.setIndentLevel(1);
XSLFTextRun r2 = p2.addNewTextRun();
r2.setText("Numbered List Item - 1");

In case we’re working with multiple lists, it’s always important to define the indentLevel to achieve a proper indentation of items.

如果我们要处理多个列表,定义indentLevel以实现项目的适当缩进总是很重要。

4.5. Tables

4.5.表

Tables are another key object in a presentation and are helpful when we want to display data.

表格是演示文稿中的另一个关键对象,当我们想显示数据时,它很有帮助。

Let’s start by creating a table:

让我们从创建一个表开始。

XSLFTable tbl = slide.createTable();
tbl.setAnchor(new Rectangle(50, 50, 450, 300));

Now, we can add a header:

现在,我们可以添加一个标头。

int numColumns = 3;
XSLFTableRow headerRow = tbl.addRow();
headerRow.setHeight(50);

for (int i = 0; i < numColumns; i++) {
    XSLFTableCell th = headerRow.addCell();
    XSLFTextParagraph p = th.addNewTextParagraph();
    p.setTextAlign(TextParagraph.TextAlign.CENTER);
    XSLFTextRun r = p.addNewTextRun();
    r.setText("Header " + (i + 1));
    tbl.setColumnWidth(i, 150);
}

Once the header is completed, we can add rows and cells to our table to display data:

一旦标题完成,我们就可以向我们的表格添加行和单元格以显示数据。

for (int rownum = 1; rownum < numRows; rownum++) {
    XSLFTableRow tr = tbl.addRow();
    tr.setHeight(50);

    for (int i = 0; i < numColumns; i++) {
        XSLFTableCell cell = tr.addCell();
        XSLFTextParagraph p = cell.addNewTextParagraph();
        XSLFTextRun r = p.addNewTextRun();
        r.setText("Cell " + (i*rownum + 1));
    }
}

When working with tables, it’s important to remind that it’s possible to customize the border and the background of every single cell.

在处理表格时,需要提醒的是,可以定制每个单元格的边框和背景。

5. Altering a Presentation

5.改动演示文稿

Not always when working on a slideshow, we have to create a new one, but we have to alter an already existing one.

在处理幻灯片时,我们并不总是要创建一个新的,而是要改变一个已经存在的。

Let’s give a look to the one that we created in the previous section and then we can start altering it:

让我们看看我们在上一节创建的那个,然后我们可以开始改变它。

presentation 1

5.1. Reading a Presentation

5.1.阅读演示文稿

Reading a presentation is pretty simple and can be done using the XMLSlideShow overloaded constructor that accepts a FileInputStream:

读取演示文稿非常简单,可以使用接受FileInputStreamXMLSlideShow重载构造函数来完成。

XMLSlideShow ppt = new XMLSlideShow(
  new FileInputStream("slideshow.pptx"));

5.2. Changing Slide Order

5.2.改变幻灯片顺序

When adding slides to our presentation, it’s a good idea to put them in the correct order to have a proper flow of slides.

在向我们的演示文稿中添加幻灯片时,最好把它们放在正确的顺序中,以便有一个适当的幻灯片流程。

When this doesn’t happen, it’s possible to re-arrange the order of the slides. Let’s see how we can move the fourth slide to be the second one:

当这种情况没有发生时,可以重新安排幻灯片的顺序。让我们看看如何将第四张幻灯片移到第二张。

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

XSLFSlide slide = slides.get(3);
ppt.setSlideOrder(slide, 1);

5.3. Deleting a Slide

5.3.删除幻灯片

It’s also possible to delete a slide from a presentation.

也可以从演示文稿中删除一张幻灯片。

Let’s see how we can delete the 4th slide:

让我们看看如何删除第四张幻灯片。

ppt.removeSlide(3);

6. Conclusion

6.结论

This quick tutorial has illustrated how to use the Apache POI API to read and write PowerPoint file from a Java perspective.

这个快速教程说明了如何使用Apache POI API从Java角度读写PowerPoint文件。

The complete source code for this article can be found, as always, over on GitHub.

本文的完整源代码可以一如既往地在GitHub上找到,over on GitHub