导出到excel功能会常做,但是导出到word功能很少做,项目遇到,在这里做一下标记。

导出到excel比较容易,excel都有固定格式也模板,但是word需要自己写模板,这里用了freemarker做模板。

具体代码如下

import freemarker.template.Configuration;
import freemarker.template.Template;
import sun.misc.BASE64Encoder; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map; public class WordUtils {
//配置信息,代码本身写的还是很可读的,就不过多注解了
private static Configuration configuration = null;
//这里注意的是利用WordUtils的类加载器动态获得模板文件的位置
// private static final String templateFolder = WordUtils.class.getClassLoader().getResource("../../").getPath() + "WEB-INF/templetes/";
// private static final String templateFolder = "d:/我的项目/lm/lm/web/src/main/webapp/WEB-INF/templates";
// private static final String templateFolder =
static {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
try {
// configuration.setDirectoryForTemplateLoading(new File(templateFolder));
configuration.setClassForTemplateLoading(WordUtils.class, "/template/");//模板文件所在路径
} catch (Exception e) {
e.printStackTrace();
}
} private WordUtils() {
throw new AssertionError();
} /**
* 具体导出功能
* @param request
* @param response
* @param map 具体数据
* @param title 导出的文件名
* @param ftlFile word模板ftl名称,对应静态代码快中:模板文件所在路径下的ftl文件
* @throws IOException
*/
public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map, String title, String ftlFile) throws IOException {
Template freemarkerTemplate = configuration.getTemplate(ftlFile);
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
// 调用工具类的createDoc方法生成Word文档
file = createDoc(map, freemarkerTemplate);
fin = new FileInputStream(file); response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件名
Calendar cal = Calendar.getInstance();
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddhhmmss");
String fileName = title + f.format(cal.getTime()) + ".doc";
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8")))); out = response.getOutputStream();
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1; // 通过循环将读入的Word文件的内容输出到浏览器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch(Exception e){
e.printStackTrace();
}finally {
if(fin != null) fin.close();
if(out != null) out.close();
if(file != null) file.delete(); // 删除临时文件
}
} private static File createDoc(Map<?, ?> dataMap, Template template) {
String name = "sellPlan.doc";
File f = new File(name);
Template t = template;
try {
// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
w.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
return f;
} //获得图片的base64码
@SuppressWarnings("deprecation")
private static String getImageBase(String src, HttpServletRequest request, HttpServletResponse response) {
if(src==null||src==""){
return "";
}
File file = new File(request.getRealPath("/")+src.replace(request.getContextPath(), ""));
if(!file.exists()) {
return "";
}
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
}

作为一个工具类,调用还是很简单的,自己构建数据后,在控制器端一行代码就可以了。

WordUtils.exportMillCertificateWord(request, response, outMap, testpager.getTPNAME(), "exportword.ftl");

其中outMap就是自己的数据,map键值对,在模板中通过${key}显示,其中判断语句,循环语句等需要参考freemarker的具体写法。

需要说明的是:

1、工具类中直接写入了response对象,所以在controller中调用需要返回void。

2、注意引入模板时的路径问题。

configuration.setDirectoryForTemplateLoading(new File(templateFolder));
configuration.setClassForTemplateLoading(WordUtils.class, "/template/");//模板文件所在路径

都可以引入路径,第一种是绝对路径,第二种是相对路径,代码中用了第二种。找到静态资源的template文件夹下的模板文件。

总的说没技术含量,但是ftl模板没有预览,调试很麻烦,网上查也灭有好的方法,希望看官能够提供更好的方式。

导出到word的更多相关文章

  1. Java 实现HTML富文本导出至word完美解决方案

    一. 问题的提出 最近用java开发一个科技项目信息管理系统,里面有一个根据项目申请书的模板填写项目申报信息的功能,有一个科技项目申请书word导出功能. 已有的实现方式:采用标准的jsp模板输出实现 ...

  2. java导出生成word(类似简历导出)

    参考帖子: http://www.cnblogs.com/lcngu/p/5247179.html http://www.cnblogs.com/splvxh/archive/2013/03/15/2 ...

  3. java导出生成word

    最近做的项目,需要将一些信息导出到word中.在网上找了好多解决方案,现在将这几天的总结分享一下. 目前来看,java导出word大致有6种解决方案: 1:Jacob是Java-COM Bridge的 ...

  4. PowerDesigner将PDM导出生成WORD文档

    PowerDesigner将PDM导出生成WORD文档 环境 PowerDesigner15 1.点击Report Temlates 制作模板 2.如果没有模板,单击New图标创建.有直接双击进入. ...

  5. C#将html导出到word(基于wps)

    由于客户需要,我们需要实现将网页导出到word中的功能,在此过程中,尝试使用过openoffice.itext.wordapi等各种方法,都不尽如人意.openoffice导出的问题图片信息在word ...

  6. HTML页面导出为Word

    protected void btnExport_Click(object sender, EventArgs e) { string strFileName = DateTime.Now.ToStr ...

  7. gridview数据导出到word和excel以及excel的导入

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI ...

  8. javascript下用ActiveXObject控件替换word书签,将内容导出到word后打印第1/2页

    由于时间比较紧,没多的时候去学习研究上述工具包,现在用javascript操作ActiveXObject控件,用替换word模板中的书签方式解决. 最近有需求将数据导出到word里,然后编辑打印. 想 ...

  9. 将HTML导出生成word文档

    前言: 项目开发中遇到了需要将HTML页面的内容导出为一个word文档,所以有了这边随笔. 当然,项目开发又时间有点紧迫,第一时间想到的是用插件,所以百度了下.下面就介绍两个导出word文档的方法. ...

  10. mvc中html导出成word下载-简单粗暴方式

    由于工作需求,需要把html简历页导出成word下载.网上搜索了很多解决方案,基本都是用一些插件,然后写法也很麻烦,需要创建模板什么的. 固定替换值  代码一大堆.但是对于我的需求来说  并没有什么用 ...

随机推荐

  1. 一键脚本清理DEBIAN系统无用组件 减少系统资源

    虽然如今我们选择服务器资源都比较多,以前我们看到很多128MB内存.甚至32MB内存的建站网站,感觉特别羡慕.其实这些也不是难事,相比之下,DEBIAN系统比CENTOS系统占用资源少,然后我们需要进 ...

  2. 201771010134杨其菊《面向对象程序设计java》第九周学习总结

                                                                      第九周学习总结 第一部分:理论知识 异常.断言和调试.日志 1.捕获 ...

  3. PowerDesigner code、name显示设置 及 同时显示办法

    菜单->Tool->Model Options->Name Convention->右侧display中选择显示name还是code. 不支持同时显示,但可以选择显示code, ...

  4. 给pdf添加导航目录

    给pdf添加导航目录 我们下载pdf书籍经常需要以下导航功能,没有导航的pdf根本看不下,接下来会分享我添加导航的方法 首先需要下载工具软件,链接: http://t.cn/Exyss1G 打开软件, ...

  5. 浅谈 drop、truncate和delete的区别

    (1)DELETE语句执行删除的过程是每次从表中删除一行,并且同时将该行的删除操作作为事务记录在日志中保存以便进行进行回滚操作. TRUNCATE TABLE 则一次性地从表中删除所有的数据并不把单独 ...

  6. Filter的介绍及使用

    转:http://blog.csdn.net/zhaozheng7758/article/details/6105749 一.Filter的介绍及使用 什么是过滤器? 与Servlet相似,过滤器是一 ...

  7. HttpWebRequest.AddRange 支持long类型

    很久很久以前,在哪个FAT32格式还流行的年代,文件大小普遍还没超过4G的年代,.Net已经出来了. 而那时候.Net实现的HTTP断点续传协议,还没预料到如此普及(我猜的).那时候的HttpWebR ...

  8. 微信for linux

    http://blog.csdn.net/sunxiang_520/article/details/51637551

  9. MyBatis 一级缓存,二级缓存,延迟加载设置

       1  什么是延迟加载  resultMap中的association和collection标签具有延迟加载的功能. 延迟加载的意思是说,在关联查询时,利用延迟加载,先加载主信息.使用关联信息时再 ...

  10. MongoDB + Express 环境搭建记

    最近项目需要使用 MongoDB,所以不得不搭建 MongoDB 环境,此文记录搭建过程及使用过程中需要了解的问题. Linux + Windows 混合搭建调试 MongoDB 记录 版本介绍 : ...