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 ...
随机推荐
- Python中的单例模式的几种实现方式的优缺点及优化
单例模式 单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在.当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场. ...
- Python2和Python3中的字符串编码问题解决
Python2和Python3在字符串编码上是有明显的区别. 在Python2中,字符串无法完全地支持国际字符集和Unicode编码.为了解决这种限制,Python2对Unicode数据使用了单独的字 ...
- nmon进行性能分析
在压测的时候,搭配nmon,可以很好的记录机器cpu情况,内存情况 下载 需要下载nmon和nmon analyser,到各自的官网下载. nmon可以根据自己的操作系统版本下载二进制文件,免去安装. ...
- eclipse从git拉去出现红色方块的解决办法
1:由于错误已经解决,这里借了一副图,主要是显示这个红色方块,然后贴一下解决方法,日后好脑补: 大家一看肯定都是冲突了,我也是第一次遇到这种错误,贴一下(鼠标右击项目找到如下的Reset): 然后红色 ...
- 盒模型 bug 与触发 bfc
一.margin合并 css经典bug 两个块级元素 分别设置 margin-bottom 和 margin-top 并不能达到预期效果 <style> .up{ width: 200 ...
- 海康、大华IPC的rtsp格式
海康: rtsp://[username]:[password]@[ip]:[port]/[codec]/[channel]/[subtype]/av_stream说明:username: 用户名.例 ...
- Linux系统调用过程
1 系统调用的作用 系统调用是操作系统提供给用户(应用程序)的一组接口,每个系统调用都有一个对应的系统调用函数来完成相应的工作.用户通过这个接口向操作系统申请服务,如访问硬件,管理进程等等. 应用程序 ...
- Python基础知识拾遗
彻底搞清楚python字符编码 python的super函数
- 关于Gson定制的分析
首先,为什么需要定制呢?很多同学可能觉得默认的不也挺好的嘛?最开始,我也是觉得的,而且我们一开始也是用默认的解析方式的,因为我们与外部约定的数据格式一直都比较稳定.但当外部数据不稳定,那么Gson默认 ...
- 【C#系列】浅谈委托和委托
本篇文章更适合具有一定开发经验,一定功底,且对底层代码有所研究的朋友!!! 本篇文章主要采用理论和代码实例相结合方法来论述委托和事件,涉及到一些边界技术,如软件架构的OCP原则(开-闭原则), 软件架 ...