通过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"));
//招标文件技术部分审批表 附件3
allTemplates.put("ResourceOutSendFile",configuration.getTemplate("ResourceOutSendFile.ftl"));
//招标文件技术部分审批表 附件4
allTemplates.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() {
@Override
public 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文档发现内容位置问题。如果有博友知道的话,欢迎一起交流。
以下附上两个工具类的下载链接。