导出到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. Ubuntu16.04 静态IP设置

    为VMware虚拟机内安装的Ubuntu 16.04设置静态IP地址NAT方式 1.安装环境 VMware 12 Ubuntu 16.04 x86_64 2.在VMware中,配置网络环境 VMwar ...

  2. python 杨辉三角实现逻辑

    程序输出需要实现如下效果: [1] [1,1] [1,2,1] [1,3,3,1] ...... 方法:迭代,生成器 def triangles() L = [1] while True: yiled ...

  3. Java高级应用简笔

    1. Annotation 使用范围: package, class, method, field 常用: @Override, @Deprecated, @SuppressWarnings 自定义注 ...

  4. Codeforces 1083C Max Mex

    Description 一棵\(N\)个节点的树, 每个节点上都有 互不相同的 \([0, ~N-1]\) 的数. 定义一条路径上的数的集合为 \(S\), 求一条路径使得 \(Mex(S)\) 最大 ...

  5. ASP .NetCore 部署500错误 查看异常详情

    部署.net core 网站后,访问报错:500 按照教程设置完成,但访问时总是提示 服务器内部错误,没有详细的异常信息,无从下手. 解决办法: 1.在站点根目录下按住shift+鼠标右键,选择在此处 ...

  6. chrome gps位置模拟设置

    chrome gps位置模拟设置 调试公众号页面定位,Edge 虽好实现方便,介于界面实在不符合我的调试习惯  遂上度娘寻觅chrome模拟GPS方法 找了好几个帖子,发现新版本已经不再试用.不得感叹 ...

  7. thymeleaf拆分头部(head)显示异常问题

    问题描述: 刚用thymeleaf不久,考虑到公共头部的导入css,js代码,需要拆分. 拆分之后,bootstrap-select下拉多选框出现“样式异常”,本认为是头部拆分问题,css样式未导入成 ...

  8. Jmeter监控服务器-CPU,Memory,Disk,Network性能指标

    本文主要说一下如何通过JMeter插件来监控服务器CPU.内存.磁盘.网络等相关资源. 一.下载 首先进入网址https://jmeter-plugins.org/downloads/old/  下载 ...

  9. python 调用shell hive sql

    def generate_csv_source(data_file): #判断文件是否存在 if not os.path.exists(data_file): # 拉取hive表数据 cmd_sql ...

  10. 谷歌浏览器运行Flash

    最近有人问我谷歌浏览器的flash总是要点击手动运行才可以使用.看了很多网上很多教程,并没有比较好的解决方案. 自己找了相关资料后,找到了一个比较好的完整的.特此在这边放出来给大家使用. 新建记事本, ...