Spring MVC中使用POI导出Word
内容绝大部分来源于网络
准备工作
- 准备【XwpfTUtil】工具类(来源于网络)
- 准备word模版
下载【XwpfTUtil】工具类
import org.apache.poi.xwpf.usermodel.*; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; public class XwpfTUtil {
/**
* 替换段落里面的变量
*
* @param doc 要替换的文档
* @param params 参数
*/
public void replaceInPara(XWPFDocument doc, Map<String, Object> params) {
Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
XWPFParagraph para;
while (iterator.hasNext()) {
para = iterator.next();
this.replaceInPara(para, params);
}
} /**
* 替换段落里面的变量
*
* @param para 要替换的段落
* @param params 参数
*/
public void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
List<XWPFRun> runs;
Matcher matcher;
if (this.matcher(para.getParagraphText()).find()) {
runs = para.getRuns(); int start = -1;
int end = -1;
String str = "";
for (int i = 0; i < runs.size(); i++) {
XWPFRun run = runs.get(i);
String runText = run.toString();
System.out.println("------>>>>>>>>>" + runText);
if ('$' == runText.charAt(0)&&'{' == runText.charAt(1)) {
start = i;
}
if ((start != -1)) {
str += runText;
}
if ('}' == runText.charAt(runText.length() - 1)) {
if (start != -1) {
end = i;
break;
}
}
}
System.out.println("start--->"+start);
System.out.println("end--->"+end); System.out.println("str---->>>" + str); for (int i = start; i <= end; i++) {
para.removeRun(i);
i--;
end--;
System.out.println("remove i="+i);
} for (String key : params.keySet()) {
if (str.equals(key)) {
para.createRun().setText((String) params.get(key));
break;
}
} }
} /**
* 替换表格里面的变量
*
* @param doc 要替换的文档
* @param params 参数
*/
public void replaceInTable(XWPFDocument doc, Map<String, Object> params) {
Iterator<XWPFTable> iterator = doc.getTablesIterator();
XWPFTable table;
List<XWPFTableRow> rows;
List<XWPFTableCell> cells;
List<XWPFParagraph> paras;
while (iterator.hasNext()) {
table = iterator.next();
rows = table.getRows();
for (XWPFTableRow row : rows) {
cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
paras = cell.getParagraphs();
for (XWPFParagraph para : paras) {
this.replaceInPara(para, params);
}
}
}
}
} /**
* 正则匹配字符串
*
* @param str
* @return
*/
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
} /**
* 关闭输入流
*
* @param is
*/
public void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 关闭输出流
*
* @param os
*/
public void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Word模版
需要填充的内容已${xxx}代替

完整步骤
一:页面中点击导出word按钮
//导出word
$("#导出按钮的ID").click(function () {
//请使用 window.location.href 发送请求。
window.location.href = "/exportfoWord"
});
二: 后台Controller
@RequestMapping("exportWord")
@ResponseBody
public String exportWord(HttpServletRequest request, HttpServletResponse response){
Service.exportWord(request,response);
return "success";
}
三:后台service
public void exportWord(HttpServletRequest request, HttpServletResponse response) {
XWPFDocument doc = null;
InputStream is=null;
OutputStream os = null;
XwpfTUtil xwpfTUtil = new XwpfTUtil();
try{
Map<String, Object> params = new HashMap<String, Object>();
params.put("${name}", "张三");
String fileNameInResource="temp.docx";//word模版的名字
is = getClass().getClassLoader().getResourceAsStream(fileNameInResource);//会在跟路径下面查看temp.doc文件。(web项目中为classes文件下面)
doc = new XWPFDocument(is);
xwpfTUtil.replaceInPara(doc, params);
//替换表格里面的变量
xwpfTUtil.replaceInTable(doc, params);
os = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition","attachment;filename=export-Word-name.docx");//filename为导出的word的名字
doc.write(os);
}catch (Exception e){
logger.debug(e.getMessage());
}finally {
xwpfTUtil.close(os);
xwpfTUtil.close(is);
try {
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
导出效果

Spring MVC中使用POI导出Word的更多相关文章
- Http请求中Content-Type讲解以及在Spring MVC中的应用
引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值 ...
- Spring mvc 中使用 kaptcha 验证码
生成验证码的方式有很多,个人认为较为灵活方便的是Kaptcha ,他是基于SimpleCaptcha的开源项目.使用Kaptcha 生成验证码十分简单并且参数可以进行自定义.只需添加jar包配置下就可 ...
- Http请求中Content-Type讲解以及在Spring MVC中的应用【转】
完全引用自: http://blog.csdn.net/blueheart20/article/details/45174399#t1 此文讲得很清晰,赞! 引言: 在Http请求中,我们每天都在 ...
- java工具类POI导出word
1.新建一个word,里面填写内容,如: 2.导出wordjava类 /** * POI导出word测试 * @throws Exception */ @RequestMapping(value=&q ...
- Http请求中Content-Type和Accept讲解以及在Spring MVC中的应用
在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值,以及在 ...
- [转]Http请求中Content-Type讲解以及在Spring MVC中的应用
本文转自:http://blog.csdn.net/blueheart20/article/details/45174399 引言: 在Http请求中,我们每天都在使用Content-type来指定不 ...
- 使用POI导出Word(含表格)的实现方式及操作Word的工具类
.personSunflowerP { background: rgba(51, 153, 0, 0.66); border-bottom: 1px solid rgba(0, 102, 0, 1); ...
- Spring mvc中@RequestMapping 6个基本用法
Spring mvc中@RequestMapping 6个基本用法 spring mvc中的@RequestMapping的用法. 1)最基本的,方法级别上应用,例如: Java代码 @Reques ...
- spring mvc中使用freemark的一点心得
参考文档: FreeMarker标签与使用 连接http://blog.csdn.net/nengyu/article/details/6829244 freemarker学习笔记--指令参考: ht ...
随机推荐
- 什么是ObjCTypes?
先看一下消息转发流程: 在forwardInvocation这一步,你必须要实现一个方法: - (NSMethodSignature *)methodSignatureForSelector:(SEL ...
- px-rem自适应转换
当前团队开发过程,存在2种度量单位(px.rem)各有说辞px:各个终端统一大小,简单明了,未尝不可!rem:大屏幕显示大字体,小屏幕显示小字体,渐进增强视觉感.业界各种写法都有,不逐一讨论.团队呼声 ...
- 极光配置-》thinkphp3.2.3
1,小白我搞了几天,终于得到了这样的结果(我猜应该是成功了吧). { "body": { "sendno": "100000", " ...
- 网络时钟服务器,NTP授时设备,北斗网络校时服务器,GPS时间同步器
网络时钟服务器,NTP授时设备,北斗网络校时服务器,GPS时间同步器 网络时钟服务器,NTP授时设备,北斗网络校时服务器,GPS时间同步器 论述当下网络时间同步的重要性 北京华人开创科技发展有限公 ...
- wifipineapple插件:codeInject的使用
如果在中间人攻击的时候, 能在用户的网页中插入任意代码, 可以说已经完成一半了 wifipineapple有个codeInject插件, 可以让连上这个网络所有设备浏览网页的时候, 在网页中插入任意h ...
- App开发 对生命周期的处理
//获取到当前所在的视图 - (UIViewController *)presentingVC:(UIApplication *)application{ UIWindow * window = ap ...
- 通过yum安装mysql数据
1. 卸载掉原有mysql 因为mysql数据库在Linux上实在是太流行了,所以目前下载的主流Linux系统版本基本上都集成了mysql数据库在里面,我们可以通过如下命令来查看我们的操作系统上是否已 ...
- fastboot模式
快速启动. 在安卓手机中fastboot是一种比recovery更底层的刷机模式. fastboot是一种线刷,就是使用USB数据线连接手机的一种刷机模式. recovery是一种卡刷,就是将刷机包放 ...
- 关于Gson定制的分析
首先,为什么需要定制呢?很多同学可能觉得默认的不也挺好的嘛?最开始,我也是觉得的,而且我们一开始也是用默认的解析方式的,因为我们与外部约定的数据格式一直都比较稳定.但当外部数据不稳定,那么Gson默认 ...
- Smart-image通过SoftReference提高性能
文章导读: 文件介绍了常见的图片下载开源插件smart-image, 由于移动设备硬件受限,因此Android的相关app都要考虑到性能的关系, 所以很多的第三方插件都使用到了缓存cache技术,本人 ...