通过POI和jacob可以实现word文档的在线预览和下载。

首先,引入以下maven依赖。

        <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.15</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>xdocreport</artifactId><version>1.0.6</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.3</version></dependency>

以上maven依赖主要是POI的相关jar包,话不多说,开始上课。

首先通过word模板实现word文档的数据填充,在下载生成的word文档。

(一)生成word模板

打开word文档,在需要填充数据的地方以${}的方式进行填写。

将该word文档另存为xml文件。

通过记事本或者其他编辑工具(我用的是Notepad++)代开xml文件并编辑如下:

保存之后把xml文件另存为ftl文,该文件便是word的模板。

(二)模板准备准备好了,开始撸代码。

package bingosoft.metro.sendfile.utils;import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import freemarker.template.Configuration;
import freemarker.template.Template;import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;public class WordGenerator {private static Configuration configuration = null;private static Map<String, Template> allTemplates = null;private static final String templateFolder = "D:\\Test\\Template\\";static {configuration = new Configuration();configuration.setDefaultEncoding("utf-8");
//        configuration.setClassForTemplateLoading(WordGenerator.class, "D:\\Test\\Template");try{configuration.setDirectoryForTemplateLoading(new File(templateFolder));}catch(Exception e){e.printStackTrace();}allTemplates = new HashMap<String,Template>();   // Java 7 钻石语法try {//南宁轨道交通集团有限责任公司方案优化审查申请表allTemplates.put("GroupGHSendFile", configuration.getTemplate("GroupGHSendFile.ftl"));//南宁轨道交通集团有限责任公司方案优化审批表allTemplates.put("GroupJWSendFile",configuration.getTemplate("GroupJWSendFile.ftl"));//施工图变更申请表(业主方)allTemplates.put("GroupTWSendFile",configuration.getTemplate("GroupTWSendFile.ftl"));//  施工图变更申请表(非业主方I、II、III类)allTemplates.put("GroupDWSendFile",configuration.getTemplate("GroupDWSendFile.ftl"));//施工图变更申请表(非业主方IV类)allTemplates.put("GroupInSendFile",configuration.getTemplate("GroupInSendFile.ftl"));//工程洽商审批表allTemplates.put("ResourceInSendFile",configuration.getTemplate("ResourceInSendFile.ftl"));//招标文件技术部分审批表 附件3allTemplates.put("ResourceOutSendFile",configuration.getTemplate("ResourceOutSendFile.ftl"));//招标文件技术部分审批表 附件4allTemplates.put("OperateInSendFile",configuration.getTemplate("OperateInSendFile.ftl"));
//            allTemplates.put("OperateOutSendFile",configuration.getTemplate("OperateOutSendFile.ftl"));
//            allTemplates.put("ConstructInSendFile",configuration.getTemplate("ConstructInSendFile.ftl"));
//            allTemplates.put("ConstructOutSendFile",configuration.getTemplate("ConstructOutSendFile.ftl"));} catch (IOException e) {e.printStackTrace();throw new RuntimeException(e);}}private WordGenerator() {throw new AssertionError();}public static File createDoc(Map<?, ?> dataMap, String pathAndFileName) {//创建文件File f = new File(pathAndFileName);//获取类型String type = (String) dataMap.get("appCode");//类型模板Template t = allTemplates.get(type);try {Writer w = new FileWriter(f);t.process(dataMap, w);w.close();} catch (Exception ex) {ex.printStackTrace();throw new RuntimeException(ex);}return f;}
public static void docToDocx(String pathAndFileName,String targetFile){//Word.Application代表COM OLE编程标识,可查询MSDN得到ActiveXComponent activeXComponent = new ActiveXComponent("Word.Application");//设置Word不可见activeXComponent.setProperty("Visible", false);//调用Application对象的Documents属性,获得Documents对象Dispatch dispatches = activeXComponent.getProperty("Documents").toDispatch();Dispatch dispatch = Dispatch.call(dispatches, "Open", pathAndFileName).getDispatch();Dispatch.call(dispatch, "SaveAS", targetFile, 12);//关闭打开的Word文件    Dispatch.call(dispatch, "Close", true);//关闭Word应用程序    activeXComponent.invoke("Quit", 0);}
}

通过模板读取${}的位置,并通过map集合将数据传进去上面的createDoc()方法,生成word文档。

不过此时生成的word文档依然是xml格式的,通过docToDocx()方法可以实现在xml格式的文档转化为docx格式的文档。

不过需要对应的jacob依赖。

jacob我采用的是jacob-1.19,在引入jacob的依赖包之前,需要先将jacob的jar包和.dll文件放到相应的位置。

以下链接是jacob-1.19的下载链接,你也可以去官网下载。

https://download.csdn.net/download/weixin_42311540/10763277

解压文件之后,会有

将jacob的jar包保存到jdk的jre的bin目录下,E:\JAVA\Java\jre8\bin

将相关的dll文件保存到jdk的jre目录下的ext文件目录下,E:\JAVA\Java\jre8\lib\ext

接下来便是在maven中导入相关的jar包,

接下来,word的文档下载便实现了。

(三)生成的word文档我们可以再转化为html页面。

代码如下:

package bingosoft.metro.sendfile.utils;import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;public class HtmlGenerator{public static void wordToHtml(String path,String fileName) throws Exception{File file = new File(path+fileName);InputStream inputStream = new FileInputStream(file);BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);//处理2007版本if(file.getName().endsWith(".docx")||file.getName().endsWith(".DOCX")){XWPFDocument xwpfDocument = new XWPFDocument(bufferedInputStream);System.out.println(xwpfDocument.getTables());File imageFolderFile = new File(path);XHTMLOptions options = XHTMLOptions.create().URIResolver( new BasicURIResolver("./"));options.setExtractor(new FileImageExtractor(imageFolderFile));OutputStream out = new FileOutputStream(new File(path+fileName.substring(0,fileName.indexOf(".")+1)+"html"));XHTMLConverter.getInstance().convert(xwpfDocument, out, options);out.close();}else{//处理2003版本HWPFDocument hwpfDocument = new HWPFDocument(new POIFSFileSystem(file,false));WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());wordToHtmlConverter.setPicturesManager(new PicturesManager() {@Overridepublic String savePicture(byte[] bytes, PictureType pictureType, String s, float v, float v1) {return s;}});wordToHtmlConverter.processDocument(hwpfDocument);List pics = hwpfDocument.getPicturesTable().getAllPictures();if(pics != null){for(int i=0;i<pics.size();i++){Picture pic = (Picture) pics.get(i);try{pic.writeImageContent(new FileOutputStream(path+pic.suggestFullFileName()));}catch(Exception e){e.printStackTrace();}}}Document htmlDocument = wordToHtmlConverter.getDocument();ByteArrayOutputStream outStream = new ByteArrayOutputStream();DOMSource domSource = new DOMSource(htmlDocument);StreamResult streamResult = new StreamResult(outStream);TransformerFactory tf = TransformerFactory.newInstance();Transformer serializer = tf.newTransformer();serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");serializer.setOutputProperty(OutputKeys.INDENT, "yes");serializer.setOutputProperty(OutputKeys.METHOD, "html");serializer.transform(domSource, streamResult);outStream.close();String content = new String(outStream.toByteArray());System.out.println(fileName.substring(0,fileName.indexOf(".")+1));FileUtils.writeStringToFile(new File(path, fileName.substring(0,fileName.indexOf(".")+1)+"html"), content, "utf-8");}}}

并且能够实现2003版本和2007版本的不同兼容。

(四)功能代码已经全部完成,接下我们进入测试。

以下是生成的word文档。

生成html的方法:

接下来生成的html文档如下:

其实生成的word文档和html文档都有瑕疵,word文档的填充内容还没有解决表格大小自适应的问题,生成的html文档发现内容位置问题。如果有博友知道的话,欢迎一起交流。

以下附上两个工具类的下载链接。

https://download.csdn.net/download/weixin_42311540/10763225

java通过POI和jacob实现word文档的在线预览和下载相关推荐

  1. SpringBoot实现本地上传Word文档并在线预览

    所需依赖 <dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</art ...

  2. java word在线预览_java 生成word文档并且在线预览的问题

    富文本? 用iText或者PD4ML直接转换为pdf [code="java"] String outputFile = "D:/Test/demo_3.pdf" ...

  3. java 预览word文档_Java实现office文档与pdf文档的在线预览功能

    最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完.压力略大.后面查找百度资料.以及在同事与网友的帮助下,四天多把它做完 ...

  4. java零碎要点010---Java实现office文档与pdf文档的在线预览功能

    最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完.压力略大.后面查找百度资料.以及在同事与网友的帮助下,四天多把它做完 ...

  5. Freemaker导出word文档并实现预览

    文章目录 使用freemaker进行生成word文档并实现预览 一.导入依赖 二.导出word文件步骤 1.将word文档转成ftl文件 2.文件数据绑定 三.导出html文件步骤 四.解析文件并生成 ...

  6. Java通过POI或Freemarker生成word文档,使用Jfreechart创建统计图表

    最近做了一个使用Java生成统计分析报告word文档的功能,有提前制作好的word文档,其中共包含了普通文本变量,普通表格,动态表格.统计图表(柱状图.饼状图.折线图等),在此记录下POI和freem ...

  7. 前端实现pdf,word,doc等Office文档格式在线预览

    在做一些后台管理或者h5页面的时候 通常会遇到Office文档格式的在线预览功能.虽然看似简单,里面却隐藏着很大的坑.简单是因为现在有各种插件可以下载实现,坑是因为涉及到一些兼容性和安全性等各种千奇百 ...

  8. WEB端和微信小程序端的文档文件在线预览方法

    文件的在线预览方式汇总 文件在线预览功能可以提高用户体验,值得加入. 一般常见的文件有office套装.pdf.txt.md.和音视频. 音视频的预览是单独一块,今天主要说说文档文件的在线预览功能. ...

  9. vue 在线预览、下载word、pdf文件

    vue 在线预览.下载word.pdf文件 最近项目用vue-cli3要实现word和pdf文档的在线预览和下载,在网上看到各位大佬们各种办法,发现踩坑无数,还是没弄出来,最后发现还是是自己想复杂了 ...

最新文章

  1. github RL: DP
  2. php selected,php-多个选择字段-多次使用selected =“ selected”
  3. C#判断一个字符串是否全部为空格的一个简单方法
  4. imu传感器工作原理_各种传感器工作原理汇总
  5. 不可能不爱的 XCODE 9:最新功能详尽介绍
  6. 快乐又刺激的点名小程序:滚动点名+BGM
  7. linux平台运行 mr程序,MR程序的几种提交运行模式
  8. 引用font-awesome图标库前端显示方框
  9. _iq16 c语言,[转载]【转】IQMATH使用
  10. 为了忘却的纪念---番茄花园 Windows XP 下载地址合集
  11. Program received signal SIGSEGV, Segmentation fault.
  12. 阿槽带你学Python(开篇)
  13. 详细解析ESP寄存器与EBP寄存器
  14. NUC970 裸机USBD驱动(第一章)
  15. 共享文件夹服务器内存资源不足,『excel文件打开就提示可用资源不足,无法完成此任务』共享文件夹怎么设置...
  16. Java Http 请求方式汇总
  17. 字符串的输出(C语言)
  18. sysbench 做性能测试
  19. 建议收藏 | H.265编码原理入门
  20. WIFI管家实现原理:局域网设备扫描

热门文章

  1. Linux云计算-01_介绍以及Linux操作系统安装
  2. DL:基于神经网络的深度学习模型的总概览简介(DNN/CNN/RNN等)、各种网络结构对比、案例应用对比之详细攻略
  3. nginx配置判断是pc端还是移动端并进行对应的链接跳转
  4. 惠普打印机双击之后没有扫描_Win7安装打印机后无法安装扫描仪或安装后没有扫描选项如何解决...
  5. 揭穿3个开发者和云计算神话
  6. 吾尝终日而思矣——2019.02.27
  7. C语言实现DOS系统的tree命令,DOS中的Tree命令生成目录树
  8. DocumentBuilderFactory解析xml
  9. 从瀚海到万家,易开得为净水器开辟新航道
  10. vue项目打包成app,在ios端iconfont 部分字体图标不显示