poi版本3.14.
根据poi的demo写了个简单的生成ppt的例子:
public static void makePpt(String path) throws Exception {
if (path == null) {
path = "e:/text.pptx";
}
XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide slide1 = ppt.createSlide();
XSLFTextBox shape1 = slide1.createTextBox();
Rectangle anchor = new Rectangle(10, 100, 300, 100);
shape1.setAnchor(anchor);
XSLFTextParagraph p1 = shape1.addNewTextParagraph();
XSLFTextRun r1 = p1.addNewTextRun();
r1.setFontColor(new Color(0, 200, 160));
shape1.setFillColor(Color.red);
r1.setText("text1");
XSLFTextBox shape2 = slide1.createTextBox();
Rectangle anchor2 = new Rectangle(210, 200, 300, 100);
shape2.setAnchor(anchor2);
shape2.setText("text2");
FileOutputStream out = new FileOutputStream(path);
ppt.write(out);
out.close();
ppt.close();
}
发现text1的文本框多了一个空行。text2文本框没有多空行。
使用如下代码看看到底生成了什么东西:
public static void readPpt() throws Exception {
XMLSlideShow ppt = new XMLSlideShow(new FileInputStream("e:/text.pptx"));
XSLFSlide slide1 = ppt.getSlides().get(0);
for (XSLFShape shape : slide1.getShapes()) {
if (shape instanceof XSLFTextBox) {
XSLFTextBox box = (XSLFTextBox) shape;
java.util.List ps = box.getTextParagraphs();
if (ps.size() > 0) {
java.util.List rs = ps.get(0).getTextRuns();
if (!rs.isEmpty()) {
System.out.println(rs.get(0).getRawText());
}
}
}
}
}
查看相应的代码,问题应该是出在XSLFTextParagraph p1 = shape1.addNewTextParagraph();这一句。原因应该是XSLFTextBox本身就有一个TextParagraph了。
这一行代码改成:
XSLFTextParagraph p1 =shape1.getTextParagraphs().isEmpty() ?
shape1.addNewTextParagraph() : shape1.getTextParagraphs().get(0);