Java Apache POI 小记(读取Word通过模板创建PPT)(java读取doc文件) |
您所在的位置:网站首页 › java使用poi导出word › Java Apache POI 小记(读取Word通过模板创建PPT)(java读取doc文件) |
本篇文章为你整理了Java Apache POI 小记(读取Word通过模板创建PPT)(java读取doc文件)的详细内容,包含有java如何读取word java读取doc文件 java使用poi读取excel java读取ofd文档内容 Java Apache POI 小记(读取Word通过模板创建PPT),希望能帮助你了解 Java Apache POI 小记(读取Word通过模板创建PPT)。 @ 目录起因过程确定工具功能拆分读取Word文件通过PPT模板创建PPT并填充内容将PPT转为图片总结 近期身边的一位朋友来寻求帮助,她在日常工作时,总是需要做一些重复的事情,所以想着是否能通过程序实现自动化的操作。 具体需求为,每天会收到一份固定格式的Word文件,然后根据其中的内容,填充到固定的PPT模板中,最终生成图片输出。 有了需求后,第一件事自然是在网络上查找是否有符合需要的工具使用,笔者之前用过Apache POI来操作过Excel文件的经历,因此有印象Apache POI是支持Office文件的操作,不局限于Excel文件,于是决定就用它了。(制作后期有看到一些其他的工具框架,比如Spire,但一是因为已经用POI实现了大部分功能,二是因为比如Spire的高级功能是收费的,最终还是用POI一条路走到底了) Apache POI是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office(Excel、WORD、PowerPoint、Visio等)格式档案读和写的功能(基于OLE2 Compound documents of MS-Office文件格式 )。POI本身为“Poor Obfuscation Implementation”的首字母缩写。 其中POI主要有以下功能模块: HSSF - 提供读写Microsoft Excel XLS格式档案的功能。 XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能。 HWPF - 提供读写Microsoft Word DOC97格式档案的功能。 XWPF - 提供读写Microsoft Word DOC2003格式档案的功能。 HSLF - 提供读写Microsoft PowerPoint格式档案的功能。 HDGF - 提供读Microsoft Visio格式档案的功能。 HPBF - 提供读Microsoft Publisher格式档案的功能。 HSMF - 提供读Microsoft Outlook格式档案的功能。 确定使用的工具之后,便是将需求进行功能性拆分,方便功能的独立实现。 读取Word文件,包括文字的颜色属性。 读取PPT模板,通过模板创建新的PPT,并将Word文件中读取的内容填充到新建的PPT文件中。 将PPT文件转换为图片。 读取Word文件 Apache POI支持对Word文件进行读写操作。笔者使用的3.17的版本,主要是因为开始查找相关范例的时候,网上的demo多数基于这个版本,虽然版本不是最新的,但足够实现所需要的功能。(笔者在功能完成后,有尝试使用最新版的POI,新版的实现与旧版略有不同,会导致已实现的功能报错,因为时间问题就没有深究,因此又退回了3.17的版本)。POI的Maven依赖如下所示: dependencies
dependency groupId org.apache.poi /groupId artifactId poi /artifactId version 3.17 /version /dependency !-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -- dependency groupId org.apache.poi /groupId artifactId poi-ooxml /artifactId version 3.17 /version /dependency !-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -- dependency groupId org.apache.poi /groupId artifactId poi-ooxml-schemas /artifactId version 3.17 /version /dependency !-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -- dependency groupId org.apache.poi /groupId artifactId poi-scratchpad /artifactId version 3.17 /version /dependency /dependencies
引入POI库后,便可以着手进行功能的实现了,下面的示例为读取本地磁盘的Word文件。 // 读取制定路径下的doc文件,测试时使用的是docx文件
public static ArrayList WordStrList readDoc1(String path) throws IOException { InputStream is = new FileInputStream(path); XWPFDocument doc = new XWPFDocument(is); // 获取文本内容及文本颜色 WordStr wordStr = new WordStr(run.toString(), run.getColor()); wordList.add(wordStr); sb.append(run.toString()); wordLists.add(wordList); sb.setLength(0); System.out.println("Word文件【"+path+"】加载完毕..."); return wordLists;
通过XWPFDocument可以很轻松地读取到指定的Word文件,除了Word的文本内容外,还能获取一些格式属性,笔者只需要获取对应文字的颜色即可。 通过PPT模板创建PPT并填充内容 在上一步中,我们可以读取Word文件中的内容,加以一定的解析筛选,便可以得到想要往PPT中填充的内容了。 笔者这次的PPT模板非常简单,分为封面、内容页、封底,每页都是一张底图加一个文本框,因此相对操作比较简单,参考代码如下: public static void createPPTByTemplate(String templatePath, String destPPTPath, ArrayList WordStrList contentList) {
InputStream is; OutputStream os; XMLSlideShow oPPT; try { is = new FileInputStream(templatePath); os = new FileOutputStream(destPPTPath); oPPT = new XMLSlideShow(is); } catch (IOException e) { throw new RuntimeException(e); System.out.println("创建内容页..."); Pattern indexPattern = Pattern.compile("[\\d]+、"); for (int i = 1; i contentList.size() - 1; i++) { WordStrList wsl = contentList.get(i); Matcher matcher = indexPattern.matcher(wsl.toString().substring(0, 5)); XSLFSlide contentSlide = copySlide(dPPT, baseSlide1); shapeList = contentSlide.getShapes(); for (XSLFShape shape : shapeList) { if (shape instanceof XSLFTextShape) { XSLFTextShape temp = (XSLFTextShape) shape; temp.clearText(); XSLFTextRun xslfTextRun; WordStr wStr; if (!matcher.find()) { String tempStr = wsl.get(0).getStr(); wsl.get(0).setStr(i + "、" + tempStr); for (int j = 0; j wsl.size(); j++) { wStr = wsl.get(j); xslfTextRun = temp.appendText(wStr.getStr(), false); setText(xslfTextRun, wStr.getColor(), 18.0, "等线"); temp.setHorizontalCentered(true); //将PPT写出至本地 try { dPPT.write(os); } catch (IOException e) { throw new RuntimeException(e); System.out.println("PPT【" + destPPTPath + "】生成结束,生成PPT页数:" + dPPT.getSlides().size() + "页...");
public static XSLFSlide copySlide(XMLSlideShow slideShow, XSLFSlide slide) {
XSLFSlide xslfSlide = slideShow.createSlide(); List XSLFShape shapes = slide.getShapes(); for (XSLFShape shape : shapes) { xslfSlide.importContent(shape.getSheet()); return xslfSlide;
public static void setText(XSLFTextRun xslfTextRun, String color, double fontSize, String fontFamily) {
xslfTextRun.setFontColor(fromStrToARGB(color)); xslfTextRun.setFontSize(fontSize); xslfTextRun.setFontFamily(fontFamily);
public static Color fromStrToARGB(String str) {
String redStr = str.substring(0, 2); String greenStr = str.substring(2, 4); String blueStr = str.substring(4, 6);
因为笔者源码中含有一些自己文件格式的解析,所以就没有贴出全部的内容了。这里的PPT创建主要分为几步,通过 XMLSlideShow 获取模板文件、通过XMLSlideShow 创建新的PPT文件,通过模板向新建PPT文件中创建新的页面,将之前读取到的内容填充至新建PPT中。 将PPT转为图片 该功能需要注意的是,按原尺寸绘制的PPT界面会比较模糊,可以通过等比例放大图片,使生成的图片更加清晰。 同时,目前该功能无法将第二步代码生成的PPT进行转换,可以转换正常的PPT文件,因为在拷贝模板的步骤中( public XSLFSlide importContent(XSLFSheet src)),会改变新建PPT页SlideLayout,最终导致绘制过程报错,此处目前暂未找到好的方法解决。 public static int converPPTtoImage(String pptPath, String targetImageFileDir,
String imageFormatNameString, int times) { File orignalPPTFile = new File(pptPath); //验证文件是否为pptx格式 if (!checkIsPPTFile(orignalPPTFile)) { System.out.print("待转换文件格式异常,不是pptx"); return 0; FileInputStream is = null; int imgCount = 0; File imgFileDir = new File(targetImageFileDir); //如果没有文件夹就创建文件夹 createDirIfNotExist(targetImageFileDir); try { is = new FileInputStream(orignalPPTFile); XMLSlideShow xmlSlideShow = new XMLSlideShow(is); List XSLFSlideMaster list = xmlSlideShow.getSlideMasters(); XSLFSlideLayout[] slideLayouts = list.get(0).getSlideLayouts(); is.close(); // 获取大小 Dimension pgsize = xmlSlideShow.getPageSize(); // 获取幻灯片 XSLFSlide[] slides = xmlSlideShow.getSlides().toArray(new XSLFSlide[0]); imgCount = slides.length; System.out.println("--3.slides.length--"+imgCount); for (int i = 0; i slides.length; i++) { // 创建BufferedImage对象,图像的尺寸为原来的每页的尺寸*倍数times BufferedImage img = new BufferedImage(pgsize.width * times, pgsize.height * times, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); graphics.setPaint(Color.white); graphics.scale(times, times);// 将图片放大times倍 graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); // 绘制 slides[i].draw(graphics); //图片将要存放的路径 String absolutePath = imgFileDir.getAbsolutePath() + File.separator + (i + 1) + "." + imageFormatNameString; File jpegFile = new File(absolutePath); //如果图片存在,则不再生成 if (jpegFile.exists()) { continue; // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径 FileOutputStream out = new FileOutputStream(jpegFile); // 写入到图片中去 ImageIO.write(img, imageFormatNameString, out); out.close(); return imgCount; } catch (Exception e) { e.printStackTrace(); return imgCount;
生活中有着很多重复性的工作,也许只要花少量的时间,就可以创建一个自动化的工具来协助我们更高效地完成日常工作,解放一定的时间。并且在制作工具的同时,也可以了解更多的知识。 以上就是Java Apache POI 小记(读取Word通过模板创建PPT)(java读取doc文件)的详细内容,想要了解更多 Java Apache POI 小记(读取Word通过模板创建PPT)的内容,请持续关注盛行IT软件开发工作室。 郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系QQ332078507,我们将第一时间修改或删除,多谢。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |