导出到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下载.网上搜索了很多解决方案,基本都是用一些插件,然后写法也很麻烦,需要创建模板什么的. 固定替换值 代码一大堆.但是对于我的需求来说 并没有什么用 ...
随机推荐
- NumPy学习_02 ndarray基本操作
1.算术运算符 它们只用于位置相同的元素之间,即为元素级的运算. 所得到的运算结果组成一个新的数组. 不用编写循环即可对数据执行批量运算.(矢量化) import numpy as np # 创建一个 ...
- Linux初次修改环境变量
对于刚刚从windows系统跳到Linux的小白们,相信多少都会出现一些强迫症,希望能将Linux的Terminal能调出点色彩,让其好看些.之前自己也不知道怎么按着百度的教程操作完成的,直到组里新来 ...
- ORACLE窗口函数
--ORACLE窗口函数,是针对分析用的. --create tablecreate table EMP ( empno NUMBER(4) not null, ename VARCHAR2(10), ...
- oracle service name sid , 用户 和 表空间
oracle 的四个概念: 数据库: 就是一堆静态的数据文件.注意是静态的 instance 实例: 可以类比数据库连接. 实例就是为了操作数据库而开辟的进程和内存空间,有了这个实例你才能操作数据库. ...
- Java上传和下载
1.文件的上传 [1] 简介 > 将一个客户端的本地的文件发送到服务器中保存. > 上传文件是通过流的形式将文件发送给服务器. [2] 表单的设置 > 向服务器上传一个文件时,表单要 ...
- 团队-爬虫豆瓣top250项目-模块测试过程
模块测试: 项目托管平台地址:https://github.com/gengwenhao/GetTop250.git 模块测试:"获取250排名的全部电影信息"功能,测试方法:手动 ...
- 每日一练ACM
2019.04.15 第1000题:A+B Problem Problem DescriptionCalculate A + B. InputEach line will contain two in ...
- 不支持find_element_by_name元素定位方法,抛不支持find_element_by_name元素定位方法,会抛如下错误 org.openqa.selenium.InvalidSelectorException: Locator Strategy 'name' is not supported for this session的解决
appium1.5后不支持find_element_by_name元素定位方法,会抛如下错误 org.openqa.selenium.InvalidSelectorException: Locator ...
- Unity使用代码动态给按钮赋值各个状态下的图片
一个小知识点,怕忘记,所以记录下.废话不多说,直接上代码: 未赋值之前: 使用下面代码赋值: using UnityEngine; using UnityEngine.UI; public class ...
- PIO学习
边沿捕获 PIO可以对输入进行边沿捕获,它可以捕获上升沿.下降沿和双沿,当检测到边沿时PIO会把它存在edgecapture 寄存器之内: 打开Synchronously capture 时,会生成一 ...