导出到word
导出到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的更多相关文章
- Java 实现HTML富文本导出至word完美解决方案
一. 问题的提出 最近用java开发一个科技项目信息管理系统,里面有一个根据项目申请书的模板填写项目申报信息的功能,有一个科技项目申请书word导出功能. 已有的实现方式:采用标准的jsp模板输出实现 ...
- java导出生成word(类似简历导出)
参考帖子: http://www.cnblogs.com/lcngu/p/5247179.html http://www.cnblogs.com/splvxh/archive/2013/03/15/2 ...
- java导出生成word
最近做的项目,需要将一些信息导出到word中.在网上找了好多解决方案,现在将这几天的总结分享一下. 目前来看,java导出word大致有6种解决方案: 1:Jacob是Java-COM Bridge的 ...
- PowerDesigner将PDM导出生成WORD文档
PowerDesigner将PDM导出生成WORD文档 环境 PowerDesigner15 1.点击Report Temlates 制作模板 2.如果没有模板,单击New图标创建.有直接双击进入. ...
- C#将html导出到word(基于wps)
由于客户需要,我们需要实现将网页导出到word中的功能,在此过程中,尝试使用过openoffice.itext.wordapi等各种方法,都不尽如人意.openoffice导出的问题图片信息在word ...
- HTML页面导出为Word
protected void btnExport_Click(object sender, EventArgs e) { string strFileName = DateTime.Now.ToStr ...
- gridview数据导出到word和excel以及excel的导入
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI ...
- javascript下用ActiveXObject控件替换word书签,将内容导出到word后打印第1/2页
由于时间比较紧,没多的时候去学习研究上述工具包,现在用javascript操作ActiveXObject控件,用替换word模板中的书签方式解决. 最近有需求将数据导出到word里,然后编辑打印. 想 ...
- 将HTML导出生成word文档
前言: 项目开发中遇到了需要将HTML页面的内容导出为一个word文档,所以有了这边随笔. 当然,项目开发又时间有点紧迫,第一时间想到的是用插件,所以百度了下.下面就介绍两个导出word文档的方法. ...
- mvc中html导出成word下载-简单粗暴方式
由于工作需求,需要把html简历页导出成word下载.网上搜索了很多解决方案,基本都是用一些插件,然后写法也很麻烦,需要创建模板什么的. 固定替换值 代码一大堆.但是对于我的需求来说 并没有什么用 ...
随机推荐
- Rsync未授权访问漏洞的修复
转自:https://www.cnblogs.com/KevinGeorge/p/9648028.html 配置文件/etc/rsync.conf解析: motd file -> motd文件位 ...
- python 15 常用模块三 re模块
一.正则模块 正则表达式(或 RE)是一种小型的.高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现.正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹 ...
- C++ vector动态数组
#include<vector>头文件 vector类称作向量类 百度百科的解释:https://baike.baidu.com/item/vector/3330482 我喜欢把知识点拿出 ...
- linux中tomcat startup.sh出现commond not found
问题: 前些天,再Linux提交更新代码启动tomcat时报commond not found 过程: 查了下百度,http://code2care.org/2015/-bash:-startup.s ...
- python编程之如何在Windows上安装python
一.安装python 首先检查你的系统里是否安装了python,开始菜单里点击运行输入cmd打开一个命令窗口,或键盘快捷键windows+R打开,在窗口中输入python并回车,如果出现了Python ...
- web应用/路由控制/视图函数/单表多表操作
一. 1.wen应用:BS架构的应用程序,B是浏览器,S:server(实现了wsgi协议)+ application https://www.cnblogs.com/liuqingzheng/art ...
- eclipse下Spring环境构建及插件
首先获取spring tool suite插件 获取地址http://spring.io/tools/sts/ 然后打开eclipse选择菜单栏Help下Install new software添加我 ...
- npm遇到的问题--npm install 执行报错 /bin/git submodule update -q --init --recursive
1.执行npm i 安装依赖时,报错:cannot read property 'match' of undefined 据说是npm本地缓存导致 解决方案: rm -rf package-lock. ...
- squid 正向代理 简单配置
linux 正向同步 项目上web服务器不给访问外网,迁移服务器环境又太麻烦,决定给web服务器做正向代理,刚开始使用nginx,但是https代理一直不成功,后面大佬建议使用squid来达到相同目的 ...
- 20155205 郝博雅 Exp 8 Web基础
20155205 郝博雅 Exp 8 Web基础 一.实验目标 (1).Web前端HTML(0.5分) 能正常安装.启停Apache.理解HTML,理解表单,理解GET与POST方法,编写一个含有表单 ...