java poi 操作ppt
java poi 操作ppt
可以参考:
https://www.w3cschool.cn/apache_poi_ppt/apache_poi_ppt_installation.html
http://blog.sina.com.cn/s/blog_657d630f0100nltw.html
http://blog.csdn.net/zt_fucker/article/details/52290028
http://blog.csdn.net/mike_caoyong/article/details/28651665
http://blog.csdn.net/littlebeat123/article/details/46483323
http://bbs.csdn.net/topics/380182913
http://blog.csdn.net/zhongweijian/article/details/8299531
http://www.anyrt.com/blog/list/poippt.html
具体:
1:maven 依赖:
<!--导出文件-->
<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>
java代码:
package com.dengwei.day01springboot.utils; import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.*; import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List; import static org.apache.poi.xslf.usermodel.SlideLayout.TITLE_AND_CONTENT; /**
* @Author
* @ClassName AddImgToPPt
* @Description TODO
* @Date 2018/11/17 0017 下午 3:28
* @Version 1.0
*/
public class AddImgToPPt {
public static void main(String args[]) throws IOException { // 创建ppt:
XMLSlideShow ppt = new XMLSlideShow();
//设置幻灯片的大小:
Dimension pageSize = ppt.getPageSize();
pageSize.setSize(800,700); //获取幻灯片主题列表:
List<XSLFSlideMaster> slideMasters = ppt.getSlideMasters();
//获取幻灯片的布局样式
XSLFSlideLayout layout = slideMasters.get(0).getLayout(SlideLayout.TITLE_AND_CONTENT);
//通过布局样式创建幻灯片
XSLFSlide slide = ppt.createSlide(layout);
// 创建一张无样式的幻灯片
// XSLFSlide slide = ppt.createSlide(); //通过当前幻灯片的布局找到第一个空白区:
XSLFTextShape placeholder = slide.getPlaceholder(0);
XSLFTextRun title = placeholder.setText("成都智互联科技有限公司");
XSLFTextShape content = slide.getPlaceholder(1);
// 投影片中现有的文字
content.clearText();
content.setText("图片区"); // reading an image
File image = new File("F:\\workroom\\img\\class2.jpg");
//获取图片信息:
BufferedImage img = ImageIO.read(image);
// converting it into a byte array
byte[] picture = IOUtils.toByteArray(new FileInputStream(image)); // adding the image to the presentation
XSLFPictureData idx = ppt.addPicture(picture, PictureData.PictureType.PNG); // creating a slide with given picture on it
XSLFPictureShape pic = slide.createPicture(idx);
//设置当前图片在ppt中的位置,以及图片的宽高
pic.setAnchor(new java.awt.Rectangle(360, 200, img.getWidth(), img.getHeight()));
// creating a file object
File file = new File("F:\\workroom\\img\\AddImageToPPT.pptx");
FileOutputStream out = new FileOutputStream(file);
// saving the changes to a file
ppt.write(out);
System.out.println("image added successfully");
out.close();
} }
找到给定文件夹下面的所有图片文件:
//找到当前文件夹下面的所有图片文件
private ArrayList<File> ImgList = new ArrayList<>();
public List<File> findAllImgFile(File file) throws IOException {
// File file = new File("F:\\workroom\\img");
File[] files = file.listFiles();
for (File file1 : files) {
if (file1.isDirectory()) {
findAllImgFile(file1);
} else if (ImageIO.read(file1) != null) {
ImgList.add(file1);
}
}
return ImgList;
}
项目实战运用:
package com.zhl.push.Utils; import com.mongodb.gridfs.GridFSDBFile;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.sl.usermodel.StrokeStyle;
import org.apache.poi.sl.usermodel.TextBox;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query; import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import static org.apache.poi.xslf.usermodel.SlideLayout.TITLE_AND_CONTENT; /**
* @Author
* @ClassName PPtExportUtil
* @Description TODO ppt导出检测报告
* @Date 2018/12/11 13:43
* @Version 1.0
*/
public class PPtExportUtil { public static XMLSlideShow exportPPt() throws IOException {
// 创建ppt:
XMLSlideShow ppt = new XMLSlideShow();
//设置幻灯片的大小:
Dimension pageSize = ppt.getPageSize();
pageSize.setSize(975, 730); // 创建一张无样式的幻灯片(首页)
XSLFSlide slide = ppt.createSlide();
//标题
XSLFTextBox title = slide.createTextBox(); //创建文本框
title.setAnchor(new Rectangle2D.Double(400, 100, 250, 100)); //设置文本框的位置
XSLFTextParagraph titleFontP = title.addNewTextParagraph(); //创建一个段落
XSLFTextRun titleTextRun = titleFontP.addNewTextRun(); //创建文本
titleTextRun.setText("成都肛肠医院--发布"); //设置文本类容
titleTextRun.setFontSize(26.00); //设置标题字号
// titleTextRun.setBold(true); //设置成粗体
XSLFTextParagraph titlePr = title.addNewTextParagraph();
titlePr.setSpaceBefore(-20D); // 设置与上一行的行距 :20D
titlePr.setLeftMargin(35D); //设置段落开头的空格数
titlePr.setBulletFont("宋体");
XSLFTextRun xslfTextRun = titlePr.addNewTextRun();
xslfTextRun.setText("媒体监测报告");
xslfTextRun.setFontSize(26.00);
//公司
XSLFTextBox textBox = slide.createTextBox();
textBox.setAnchor(new Rectangle2D.Double(30, 150, 300, 150));
XSLFTextRun paragraph = textBox.addNewTextParagraph().addNewTextRun();
paragraph.setText("智互联科技有限公司");
paragraph.setBold(true);
paragraph.setFontSize(30.00); // 城市
XSLFTextBox textCityBox = slide.createTextBox();
textCityBox.setAnchor(new Rectangle2D.Double(440, 390, 250, 100));
XSLFTextRun city = textCityBox.addNewTextParagraph().addNewTextRun();
city.setText("成都");
city.setFontSize(20.00);
// 时间
XSLFTextBox textTimeBox = slide.createTextBox();
textTimeBox.setAnchor(new Rectangle2D.Double(400, 420, 400, 100));
XSLFTextRun time = textTimeBox.addNewTextParagraph().addNewTextRun();
time.setText("2018年12月10日-2019年1月28日");
time.setFontSize(20.00); // 插入图片到ppt中 、每页显示两张
//测试图片数据
ArrayList<String> imgs = new ArrayList<>();
imgs.add("F:\\img\\ceshi1.jpg");
imgs.add("F:\\img\\ceshi2.jpg");
imgs.add("F:\\img\\ceshi3.jpg");
imgs.add("F:\\img\\ceshi4.jpg");
imgs.add("F:\\img\\ceshi5.jpg");
imgs.add("F:\\img\\ceshi6.jpg");
//获取图片信息:
// BufferedImage img = ImageIO.read(image);
if (imgs.size() > 0) {
for (int i = 0; i < imgs.size(); i++) {
//创建一张幻灯片
XSLFSlide slidePicture = ppt.createSlide();
//项目名字
XSLFTextBox projectNameBox = slidePicture.createTextBox();
projectNameBox.setAnchor(new Rectangle2D.Double(150, 100, 200, 200));
XSLFTextRun projectName = projectNameBox.addNewTextParagraph().addNewTextRun();
projectName.setText("万科京城");
projectName.setBold(true);
projectName.setFontSize(20.00);
//项目信息
XSLFTextBox projectInfoBox = slidePicture.createTextBox();
projectInfoBox.setAnchor(new Rectangle2D.Double(280, 100, 400, 200));
XSLFTextRun projectInfo = projectInfoBox.addNewTextParagraph().addNewTextRun();
projectInfo.setText("社区位置:" + "成都市锦江区水三接166号");
projectInfo.setFontSize(14.00);
XSLFTextRun projectType = projectInfoBox.addNewTextParagraph().addNewTextRun();
projectType.setText("社区属性:" + "商住楼");
projectType.setFontSize(14.00);
XSLFTextRun projectDdNum = projectInfoBox.addNewTextParagraph().addNewTextRun();
projectDdNum.setText("合同规定:" + "10");
projectDdNum.setFontSize(14.00);
XSLFTextRun projectPushNum = projectInfoBox.addNewTextParagraph().addNewTextRun();
projectPushNum.setText("实际发布:" + "8");
projectPushNum.setFontSize(14.00);
//发布实景图
XSLFTextBox pushPic = slidePicture.createTextBox();
pushPic.setAnchor(new Rectangle2D.Double(150, 210, 400, 100));
XSLFTextRun pushPicTxt = pushPic.addNewTextParagraph().addNewTextRun();
pushPicTxt.setText("发布实景图:");
pushPicTxt.setFontSize(14.00); // 插入图片 、每页显示两张图片:
int h = 2;
for (int k = 0;k<h;k++){
if(i<imgs.size()){
byte[] picture2 = IOUtils.toByteArray(new FileInputStream(imgs.get(i++)));
XSLFPictureData idx2 = ppt.addPicture(picture2, PictureData.PictureType.JPEG);
XSLFPictureShape pic2 = slidePicture.createPicture(idx2);
if(k==0){
pic2.setAnchor(new java.awt.Rectangle(150, 260, 200, 240));
}else if (k==1){
pic2.setAnchor(new java.awt.Rectangle(400, 260, 200, 240));
}
}
}
if(i>0){
i=i-1;
}
}
} System.out.println("image added successfully");
return ppt;
} }
controller:
@Controller
@RequestMapping("ppt")
public class PPTExportController { @RequestMapping("export")
public void exportPPt(HttpServletResponse response, HttpServletRequest request) throws IOException {
XMLSlideShow xmlSlideShow = PPtExportUtil.exportPPt(); String fileName = "a.ppt";
//处理中文文件名乱码
if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
|| request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
//非IE浏览器的处理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
} response.setContentType("application/vnd.ms-powerpoint");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
xmlSlideShow.write(response.getOutputStream());
}
}
场景2:根据ppt模板导出ppt
注意:如果是springboot项目打成jar后不能使用ResourceUtils.getFile(" ") 来读取资源文件,只能使用:InputStream inputStream = getClass().getClassLoader().getResourceAsStream("static/zhmd.pptx");
public static void PptExportUtil() throws IOException {
//读取模板ppt
SlideShow ppt = new XMLSlideShow(new FileInputStream(ResourceUtils.getFile("classpath:static/zhmd.pptx")));
//提取文本信息
List<XSLFSlide> slides = ppt.getSlides();
// SlideShow slideShow = copyPage(slides.get(1), ppt,2);
for (XSLFSlide slide : slides) {
List<XSLFShape> shapes = slide.getShapes();
for(int i=0;i<shapes.size();i++){
Rectangle2D anchor = shapes.get(i).getAnchor();
if (shapes.get(i) instanceof XSLFTextBox) {
XSLFTextBox txShape = (XSLFTextBox) shapes.get(i);
if (txShape.getText().contains("{schemeName}")) {
// 替换文字内容.用TextRun获取替换的文本来设置样式
TextRun rt = txShape.setText(txShape.getText().replace("{schemeName}", "测试方案"));
rt.setFontColor(Color.BLACK);
rt.setFontSize(20.0);
rt.setBold(true);
rt.setFontFamily("微软雅黑");
}
else if (txShape.getText().contains("{time}")) {
TextRun textRun = txShape.setText(txShape.getText().replace("{time}", "2019-1-19"));
textRun.setFontColor(Color.BLACK);
textRun.setFontSize(20.0);
textRun.setFontFamily("微软雅黑");
} else if (txShape.getText().contains("{projectAdd}")) {
TextRun textRun = txShape.setText(txShape.getText().replace("{projectAdd}", "成都市经江区"));
textRun.setFontColor(Color.BLACK);
textRun.setFontSize(16.0);
textRun.setFontFamily("微软雅黑");
} else if (txShape.getText().contains("{rzl}")) {
TextRun textRun = txShape.setText(txShape.getText().replace("{rzl}", "90%"));
textRun.setFontColor(Color.BLACK);
textRun.setFontSize(16.0);
textRun.setFontFamily("微软雅黑");
}
else if (txShape.getText().contains("{cg}")) {
TextRun textRun = txShape.setText(txShape.getText().replace("{cg}", "30"));
textRun.setFontColor(Color.BLACK);
textRun.setFontSize(16.0);
textRun.setFontFamily("微软雅黑");
}
else if (txShape.getText().contains("{mediaImg2}")) {
byte[] bytes = IOUtils.toByteArray(new FileInputStream(ResourceUtils.getFile("classpath:static/ceshi4.jpg")));
PictureData pictureData = ppt.addPicture(bytes, XSLFPictureData.PictureType.JPEG);
XSLFPictureShape picture = slide.createPicture(pictureData);
picture.setAnchor(anchor);
}
else if (txShape.getText().contains("{mediaImg1}")) {
byte[] bytes = IOUtils.toByteArray(new FileInputStream(ResourceUtils.getFile("classpath:static/ceshi4.jpg")));
PictureData pictureData = ppt.addPicture(bytes, XSLFPictureData.PictureType.JPEG);
XSLFPictureShape picture = slide.createPicture(pictureData);
picture.setAnchor(anchor);
}
else if(txShape.getText().contains("{projectImg}")){
byte[] bytes = IOUtils.toByteArray(new FileInputStream(ResourceUtils.getFile("classpath:static/ceshi5.jpg")));
PictureData pictureData = ppt.addPicture(bytes, XSLFPictureData.PictureType.JPEG);
XSLFPictureShape picture = slide.createPicture(pictureData);
picture.setAnchor(anchor);
}
}
}
}
OutputStream outputStreams = new FileOutputStream("F:\\test2.pptx");
ppt.write(outputStreams);
}
/**
* @return
* @Author
* @Description //TODO 复制ppt中的幻灯片 ,并设置幻灯片在ppt中的位置
* @Date 2019/1/24 11:16
* @Param slide:被复制的幻灯片,ppt:ppt对象, index:复制的ppt插入到第几页
*/
public static XSLFSlide copyPage(XSLFSlide slide, XMLSlideShow ppt, int index) throws IOException {
List<XSLFShape> shapes = slide.getShapes();
XSLFSlide slide2 = ppt.createSlide();
// if (shapes.size() > 0) {
// for (XSLFShape shape : shapes) {
// slide2.importContent(shape.getSheet());
// }
// }
slide2.importContent(slide);
//排序(在PPT中的第几页)
ppt.setSlideOrder(slide2, index);
return slide2;
}
public static void main(String[] args) {
try {
PptExportUtil();
System.out.println("执行完成!!!!!!!!!");
} catch (IOException e) { e.printStackTrace(); } }
注意:返回给浏览器是一个流对象,前端页面需要通过<a href=" " > 的形式访问 或则 window.location.href='' " 访问
或者 用axios 请求文件:
axios({
url: path + '/ppt/export' + '?access_token=' + getToken(),
method: 'post',
type: 'application/vnd.ms-powerpoint',
params: {
pushDate: this.changeDate,
schemeId: val.id
},
responseType: 'blob'
}).then(response => {
const blob = new Blob([response.data])
const fileName = val.schemeName + '.pptx'
if ('download' in document.createElement('a')) { // 非IE下载
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
this.disable = false
} else { // IE10+下载
navigator.msSaveBlob(blob, fileName)
this.disable = false
}
})
3:如果PPT模板中包含表格,怎么往表格中添加数据呢??
/**
* @return
* @Author
* @Description //TODO 六福珠宝--往PPT中表格填充数据
* @Date 2019/4/21 16:41
* @Param
*/
public void insertExcelDataToPPt(XSLFSlide slide, XMLSlideShow ppt, List<Map> DataTable) throws IOException {
List<List<Map>> subListMap = getSubListMap(DataTable, 10);
int k = 1;
int p = 1;
for (int a = 0; a < subListMap.size(); a++) {
int h=1;
XSLFSlide slide1 = copyPage(slide, ppt, p);
List<XSLFShape> shapes = slide1.getShapes();
for (XSLFShape shape : shapes) {
Rectangle2D rcn = shape.getAnchor();
//ppt页中是否含有表格判断
if (shape instanceof XSLFTable) {
XSLFTable table = (XSLFTable) shape;
table.setAnchor(rcn);
for (int d = 0; d < subListMap.get(a).size(); d++) {
XSLFTableRow tr = table.getRows().get(h);
int cellSize = tr.getCells().size();
for (int j = 0; j < cellSize; j++) {
if (j == 0) {
tr.getCells().get(j).setText(String.valueOf(k));
} else if (j == 1) {
String projectName = String.valueOf(subListMap.get(a).get(d).get("projectName"));
tr.getCells().get(j).setText(projectName);
} else if (j == 2) {
String projectAdds = String.valueOf(subListMap.get(a).get(d).get("projectAdds"));
tr.getCells().get(j).setText(projectAdds);
} else if (j == 3) {
String ddNum = String.valueOf(subListMap.get(a).get(d).get("ddNum"));
tr.getCells().get(j).setText(ddNum);
} else if (j == 4) {
String sjNum = String.valueOf(subListMap.get(a).get(d).get("sjNum"));
tr.getCells().get(j).setText(sjNum);
}
}
k += 1;
h+=1;
}
}
}
p+=1;
}
ppt.removeSlide(0);
}
4:集合分割:
/**
* @return
* @Author
* @Description //TODO 集合分割
* @Date 2019/1/24 16:48
* @Param
*/
private List<List<Map>> getSubListMap(List list, int len) {
List<List<Map>> listGroup = new ArrayList<List<Map>>();
if (list.size() < len) {
listGroup.add(list);
return listGroup;
} int listSize = list.size();
//子集合的长度
int toIndex = len;
for (int i = 0; i < list.size(); i += len) {
if (i + len > listSize) {
toIndex = listSize - i;
}
List<Map> newList = list.subList(i, i + toIndex);
listGroup.add(newList);
}
return listGroup;
}
java poi 操作ppt的更多相关文章
- java poi 操作
Java POI 操作Excel(读取/写入) https://www.cnblogs.com/dzpykj/p/8417738.html Java操作Excel之Poi基本操作 https://my ...
- poi 操作 PPT,针对 PPTX--图表篇
poi 操作 PPT,针对 PPTX--图表篇 目录 poi 操作 PPT,针对 PPTX--图表篇 1.读取 PPT 模板 2.替换标题 4.替换图表数据 接下来对 ppt 内的图表进行操作,替换图 ...
- java poi操作excel 添加 锁定单元格保护
Excel的book保护是很常用的,主要是不想让别人修改Excel的时候用.这样能够避免恶意随便修改数据,提高数据的可信度. 下面介绍JAVA POI来实现设置book保护: 使用HSSFSheet类 ...
- Java 利用POI操作PPT
解析PPT文件中的图片 import java.io.File; import java.io.FileOutputStream; import org.apache.poi.hslf.HSLFSli ...
- Java POI操作Excle工具类
用到了jxl.jar和poi.jar 一些基本的操作Excel的操作方法: import java.io.File; import java.io.FileInputStream; import ja ...
- 使用POI操作PPT文档(插入文本、图片)转
1)如果是创建新的PPT文档,直接使用SlideShow和Slide类就可以,其中SlideShow表示PPT文档,Slide表示某一张幻灯片如下代码创建空的PPT文档: SlideShow ppt ...
- java poi操作创建xslx或xsl文件,存本地和进行网络传输两种方式集成
package com.java.zxf.util; import java.io.IOException; import java.io.OutputStream; import java.net. ...
- Java POI 操作Excel(读取/写入)
pom.xml依赖: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi< ...
- java poi操作excel示例代码
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io ...
随机推荐
- 周末班:Python基础之网络编程
一.楔子 你现在已经学会了写python代码,假如你写了两个python文件a.py和b.py,分别去运行,你就会发现,这两个python的文件分别运行的很好.但是如果这两个程序之间想要传递一个数据, ...
- Linux下配置nfs并远程挂载实战探讨
简单介绍: nfs是网络文件系统,允许一个节点通过网络访问远程计算机的文件系统,远程文件系统可以被直接挂载到本地,文件操作和本地没有区别,如果是局域网的nfs那么io的性能也可以保证 nfs是Netw ...
- win10下ElasticSearch5.5.1与head、Kibana、X-Pack、SQL、IK、PINYIN插件的配置安装
ElasticSearch5.5.1与插件的配置安装 Elasticsearch5.5.1安装: 下载地址https://www.elastic.co/cn/downloads/elasticsear ...
- 从HTTL模板引擎看软件设计原则
HTTL (Hyper-Text Template Language) 是一个高性能的开源JAVA模板引擎, 适用于动态HTML页面输出, 可替代JSP页面, 指令和Velocity相似.作者是阿里巴 ...
- python 项目自动生成requirements.txt文件
主要使用目的: 任何应用程序通常需要设置安装所需并依赖一组类库来满足工作要求.通过requirements.txt可以一次性安装程序所需要和依赖的包. 为工程生成requirements.txt的两种 ...
- jQuery实现单击某个标签改变样式
1.HTML代码,如下图: <p class="sc_member_recharge_form"> <span class="selected" ...
- C Programming Style 总结
对材料C Programming Style for Engineering Computation的总结. 原文如下: C Programming Style for Engineering Com ...
- springboot 出现 Connection refused: connect
总结网上的方法再结合我自己的方法 1. springCloud com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectEx ...
- Luogu5290 十二省联考2019春节十二响(贪心+启发式合并)
考虑链的做法,显然将两部分各自从大到小排序后逐位取max即可,最后将根计入.猜想树上做法相同,即按上述方式逐个合并子树,最后加入根.用multiset启发式合并即可维护.因为每次合并后较小集合会消失, ...
- 适配相关:viewpoint,@media,vw/vh,em/rem
从网易与淘宝的font-size思考前端设计稿与工作流: http://www.cnblogs.com/lyzg/p/4877277.html Rem布局的原理解析: https://yanhaiji ...