java 下载word freemaker
网上有很多优质的博文了,这里这篇博客就是记录一下字自己,写demo的历程,坑和收获
在java程序中下载word 有6中方式,此处省略(嘻嘻),不过大家公认的是 freemaker 和 PageOffice
本篇文章是用的freemaker。
下载word 的大体思路是,制作模板,封装数据,导出
一 制作模板
很简单的模板

1 首先新建word
2 文件另存为 word .xml格式。
3 用 notepad++ 或者ideal打开xml文件(我这里推荐用ideal,看着舒服些)关于格式化xml,可以在点击开的链接上格式化xml
格式化xml之后,把文件保存为ftl格式,重新再在编辑器打开。
找到其中${user.username}和${user.password},仔细分析该ftl文件可以发现,在word文档中表格的每一行在xml文件中即为一个<w:tr></w:tr>标签,而在该标签中,每一个<w:tc></w:tc>则对应一个单元格。了解这个之后,我们就要使用ftl语法对该模板文件进行改造。这里我们需要导出的是一个用户列表的文件,每个用户包含一个用户名和密码,那么这里用户所在的这一行(<w:tr></w:tr>)就需要使用ftl中的<#list></#list>标签包含起来:
<w:tr>
<w:tc>
...
用户名:
...
</w:tc>
<w:tc>
...
${user.username}
...
</w:tc>
<w:tc>
...
密码:
...
</w:tc>
<w:tc>
...
${user.password}
...
</w:tc>
</w:tr>
</#list>
到此为止,我们的ftl模板就制作完毕了。
二 接下来我们创建后台服务端的代码
代码分为3部分
1 WordUtil 为freemaker模板设置相关的内容。
2 DownloadUtil 为下载的 工具类。
3自己封装自己的数据,一般是就是从数据库中查询出的数据。。
下面贴出的代码时service层和util工具类 ,controller 没内容就不贴了。
@Service
public class DownLoadServiceImpl implements DownLoadService { @Override
public void downLoad(HttpServletResponse response, String wordName) {
Map<?, ?> root = initData(); //数据源对象
String template = "/template/UserList.ftl"; //模板文件的地址
String path = "E:\\UserList.doc"; //生成的word文档的输出地址
ByteArrayOutputStream byteArrayOutputStream = WordUtil.process(root, template);
try {
DownLoadUtil.download(byteArrayOutputStream,response,wordName);
} catch (IOException e) {
e.printStackTrace();
} } private Map<?, ?> initData() {
Map<String, Object> root = new HashMap<String, Object>(); List<User> users = new ArrayList<User>();
User zhangsan = new User("小姐姐", "倾国倾城");
User lisi = new User("沉鱼落雁", "闭月羞花");
//User wangwu = new User("王五", "789");
users.add(zhangsan);
users.add(lisi);
//users.add(wangwu); root.put("users", users);
root.put("title", "用户列表"); return root;
}
}
public class DownLoadUtil {
/**
* @param byteArrayOutputStream 将文件内容写入ByteArrayOutputStream
* @param response HttpServletResponse 写入response
* @param returnName 返回的文件名
*/
public static void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException {
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment; filename=" + returnName);
response.setContentLength(byteArrayOutputStream.size());
OutputStream outputstream = response.getOutputStream(); //取得输出流
byteArrayOutputStream.writeTo(outputstream); //写到输出流
byteArrayOutputStream.close(); //关闭
outputstream.flush(); //刷数据
}
}
public class WordUtil {
private static Configuration configuration = null;
private WordUtil() {
throw new AssertionError();
}
/**
* 根据模板生成相应的文件
* @param root 保存数据的map
* @param template 模板文件的地址
* @param
* @return
*/
public static synchronized ByteArrayOutputStream process(Map<?, ?> root, String template) {
if (null == root ) {
throw new RuntimeException("数据不能为空");
}
if (null == template) {
throw new RuntimeException("模板文件不能为空");
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String templatePath = template.substring(0, template.lastIndexOf("/"));
String templateName = template.substring(template.lastIndexOf("/") + 1, template.length());
if (null == configuration) {
configuration = new Configuration(Configuration.VERSION_2_3_23); // 这里Configurantion对象不能有两个,否则多线程访问会报错
configuration.setDefaultEncoding("utf-8");
configuration.setClassicCompatible(true);
}
configuration.setClassForTemplateLoading(WordUtil.class, templatePath);
Template t = null;
try {
t = configuration.getTemplate(templateName);
Writer w = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
t.process(root, w); // 这里w是一个输出地址,可以输出到任何位置,如控制台,网页等
w.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return outputStream;
}
}
下面是实体类
public class User {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String name, String password) {
this.name = name;
this.password = password;
}
public User() {
}
}
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
做个各个demo 参考了好几位博友的文章,在此表示感谢。
参考链接:https://www.cnblogs.com/vcmq/p/9484362.html
http://itindex.net/detail/55080-springboot-freemarker-%E6%A0%BC%E5%BC%8F
下面demo源码:链接: https://pan.baidu.com/s/1-eVO-YgBTw-xTxA4Q4EIdg 提取码: 5g8h
java 下载word freemaker的更多相关文章
- Java之word导出下载
访问我的博客 前言 最近遇到项目需求需要将数据库中的部分数据导出到 word 中,具体是在一个新闻列表中将选中的新闻导出到一个 word 中.参考了网上一些教程,实现了该功能,在此记录下来. 导出结果 ...
- Java导出freemarker实现下载word文档格式功能
首先呢,先说一下制作freemarker模板步骤, 1. 在WPS上写出所要的下载的word格式当做模板 2. 把模板内不固定的内容(例:从数据库读取的信息)写成123或者好代替的文字标注 3. 把固 ...
- java操作word,excel,pdf
在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下java对word.excel.pdf文件的读取.本篇博客只是讲解简单应 ...
- Java解析word文档
背景 在互联网教育行业,做内容相关的项目经常碰到的一个问题就是如何解析word文档. 因为系统如果无法智能的解析word,那么就只能通过其他方式手动录入word内容,效率低下,而且人工成本和录入出错率 ...
- [Java] Java读取Word文档
前言 最近需要做一些NLP 方面的工作,使用的是Java,在此总结一下使用Java读取Word(.doc)格式文件的方法. Apache基金会非常厉害,开源工具包POI就可以处理微软家的文档,甚至包括 ...
- java操作office和pdf文件java读取word,excel和pdf文档内容
在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下Java对word.excel.pdf文件的读取.本篇博客只是讲解简单应 ...
- java实现word转pdf在线预览(前端使用PDF.js;后端使用openoffice、aspose)
背景 之前一直是用户点击下载word文件到本地,然后使用office或者wps打开.需求优化,要实现可以直接在线预览,无需下载到本地然后再打开. 随后开始上网找资料,网上资料一大堆,方案也各有不同,大 ...
- 利用aspose-words 实现 java中word转pdf文件
利用aspose-words 实现 java中word转pdf文件 首先下载aspose-words-15.8.0-jdk16.jar包 引入jar包,编写Java代码 package test; ...
- java 实现word 转 pdf
java 实现word 转 pdf 不知道网上为啥道友们写的这么复杂 ,自己看到过一篇还不错的 , 自己动手改了改 ,测试一下可以用 , 希望大家可以参考一下 , 对大家有帮助 1.引入jar ...
随机推荐
- Python2中文处理纪要
python2不是以unicode作为基本代码字符类型,碰到乱码的几率是远远高于python3,但即便如此,相信很多人,也不想随意的迁移到python3,这里就总结几个我平常碰到的问题及解法. 文件中 ...
- 使用Genymotion遇到的坑_Genymotion无法启动_unable to start the virtual device
Genymotion 十分好用,以下是我使用Genymotion碰到的问题及解决办法.目前没有看到网上有完整的解决. 遇到如下图的问题: 这个问题很多人可能回去百度“the virtual devic ...
- Python接口自动化
1.unittest单元测试框架&接口介绍 2.接口测试框架设计 3.接口的安全机制 4.Mock服务介绍&实现原理 5.Jenkins使用和配置 6 .发送邮箱设置
- Python的魔法函数
概要 如何定义一个类 类里通常包含什么 各个部分解释 类是怎么来的 type和object的关系 判断对象的类型 上下文管理器 类结构 #!/usr/bin/env python # -*- codi ...
- 阿里云—Gartner 2018 亚太区WAF魔力象限唯一云WAF提供商
近日,Gartner发布亚太区2018年度Web应用防火墙(简称“WAF”)魔力象限报告,阿里云WAF凭借成熟的产品能力和完善的服务体系成功入围,且是唯一一家进入该魔力象限的云WAF提供商. 报告指出 ...
- JDK动态代理深入理解分析并手写简易JDK动态代理(下)
原文同步发表至个人博客[夜月归途] 原文链接:http://www.guitu18.com/se/java/2019-01-05/27.html 作者:夜月归途 出处:http://www.guitu ...
- Puppet部署Nginx返代示例
一.创建目录并编辑Nginx安装模块 mkdir -pv /etc/puppet/modules/nginx/{manifests,files,templates,spec,tests,lib} ]# ...
- 第18章 启动 - Identity Server 4 中文文档(v1.0.0)
IdentityServer是中间件和服务的组合.所有配置都在您的启动类中完成. 18.1 配置服务 您可以通过调用以下方法将IdentityServer服务添加到DI系统: public void ...
- 从零开始学安全(三十六)●利用python 爆破form表单
import sys import requests from requests.auth import HTTPBasicAuth def Brute_Force_Web(postData): re ...
- Python学习基础笔记(全)
换博客了,还是csdn好一些. Python学习基础笔记 1.Python学习-linux下Python3的安装 2.Python学习-数据类型.运算符.条件语句 3.Python学习-循环语句 4. ...