2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Java使用poi操作ppt

Java使用poi操作ppt

时间:2024-08-12 16:55:59

相关推荐

Java使用poi操作ppt

Java使用poi操作ppt

/md/?articleId=117926694

上一篇中写了操作文本框和插入图片

这一篇主要是如何在有模板的情况下如替换文本和修改表格

替换表示符号文本

1. 加载模板到对象中

// 模板设置到项目中resources目录下ppt文件夹ClassPathResource classPathResource = new ClassPathResource("ppt/template.pptx");InputStream inputStream = classPathResource.getInputStream();// 设置到poi框架中的对象中XMLSlideShowXMLSlideShow ppt = new XMLSlideShow(inputStream);

2.替换文本

// 获取模板中的每一页的pptList<XSLFSlide> slides = ppt.getSlides();// 遍历操作for (XSLFShape shape : shapes) {if (shape instanceof AutoShape) {AutoShape autoShape = (AutoShape) shape;String text = autoShape.getText();if (text.contains("{YEAR}")) {TextRun textRun = autoShape.setText(text.replace("{YEAR}", year));// 设置文本格式 textRun.setFontFamily("黑体");textRun.setFontSize(36.0);textRun.setFontColor(Color.RED);}}}

替换表格

表格我直接在模板中设置好了表头

// 获取模板中的每一页的pptList<XSLFSlide> slides = ppt.getSlides();// 遍历操作for (XSLFShape shape : shapes) {if (xslfShape instanceof XSLFTable) {// 获取ppt中表格对象XSLFTable xslfTable = (XSLFTable) xslfShape;// 新建一行XSLFTableRow tableRow = xslfTable.addRow();XSLFTableCell tableCell1 = tableRow.addCell();XSLFTextParagraph textParagraph1 = tableCell1.addNewTextParagraph();XSLFTextRun textRun = textParagraph1.addNewTextRun();textRun.setText("内容1");// 文本对齐textParagraph1.setTextAlign(TextParagraph.TextAlign.CENTER);// 设置文本样式setTextRunStyle(textRun);// 第二个单元格XSLFTableCell tableCell2 = tableRow.addCell();// 设置单元格格式setTableCellStyle(tableCell2);// 数据第5行的第1 2的单元格合并 参数firstrow lastrow firstCol lastColxslfTable.mergeCells(4, 4, 0, 1);}}

/*** @Description: 设置字体样式* @Author: zhy* @Date: /6/22 11:30* @Param: [textRun]* @return: void*/private void setTextRunStyle(XSLFTextRun textRun) {textRun.setFontSize(12.0);// 设置黑体textRun.setBold(false);// 设置斜体textRun.setItalic(false);// 设置字体textRun.setFontFamily("宋体");textRun.setFontColor(Color.black);}/*** @Description: 设置单元格的样式* @Author: zhy* @Date: /6/24 16:55* @Param: [tableCell]* @return: void*/private void setTableCellStyle(XSLFTableCell tableCell) {// 是背景色吗tableCell.setFillColor(Color.GRAY);// 垂直对齐方式tableCell.setVerticalAlignment(VerticalAlignment.MIDDLE);tableCell.setLeftInset(1);tableCell.setRightInset(1);tableCell.setBottomInset(1);tableCell.setTopInset(1);// 设置边框的颜色tableCell.setBorderColor(TableCell.BorderEdge.bottom, Color.BLACK);tableCell.setBorderColor(TableCell.BorderEdge.top, Color.BLACK);tableCell.setBorderColor(TableCell.BorderEdge.left, Color.BLACK);tableCell.setBorderColor(TableCell.BorderEdge.right, Color.BLACK);}

我这个是因为项目中,需要将一个excel表中导入ppt中,但是没有办法直接导入,所以在ppt中新建一个表格的表头,然后数据查询出来之后,再一行一行的填充。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。