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; }