内容绝大部分来源于网络

准备工作


  • 准备【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的更多相关文章

  1. Http请求中Content-Type讲解以及在Spring MVC中的应用

    引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值 ...

  2. Spring mvc 中使用 kaptcha 验证码

    生成验证码的方式有很多,个人认为较为灵活方便的是Kaptcha ,他是基于SimpleCaptcha的开源项目.使用Kaptcha 生成验证码十分简单并且参数可以进行自定义.只需添加jar包配置下就可 ...

  3. Http请求中Content-Type讲解以及在Spring MVC中的应用【转】

    完全引用自: http://blog.csdn.net/blueheart20/article/details/45174399#t1   此文讲得很清晰,赞! 引言: 在Http请求中,我们每天都在 ...

  4. java工具类POI导出word

    1.新建一个word,里面填写内容,如: 2.导出wordjava类 /** * POI导出word测试 * @throws Exception */ @RequestMapping(value=&q ...

  5. Http请求中Content-Type和Accept讲解以及在Spring MVC中的应用

    在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值,以及在 ...

  6. [转]Http请求中Content-Type讲解以及在Spring MVC中的应用

    本文转自:http://blog.csdn.net/blueheart20/article/details/45174399 引言: 在Http请求中,我们每天都在使用Content-type来指定不 ...

  7. 使用POI导出Word(含表格)的实现方式及操作Word的工具类

    .personSunflowerP { background: rgba(51, 153, 0, 0.66); border-bottom: 1px solid rgba(0, 102, 0, 1); ...

  8. Spring mvc中@RequestMapping 6个基本用法

    Spring mvc中@RequestMapping 6个基本用法 spring mvc中的@RequestMapping的用法.  1)最基本的,方法级别上应用,例如: Java代码 @Reques ...

  9. spring mvc中使用freemark的一点心得

    参考文档: FreeMarker标签与使用 连接http://blog.csdn.net/nengyu/article/details/6829244 freemarker学习笔记--指令参考: ht ...

随机推荐

  1. jQuery 入门

    不能正常引用jQuery-2.2.4.min.js所以代码没生效 jQuery 是一个 JavaScript 函数库.jQuery 库包含以下特性: HTML 元素选取 HTML 元素操作 CSS 操 ...

  2. HTTP2的新特性

    多路复用 二进制分帧 首部压缩(Header Compression) 服务端推送(Server Push) 请求优先级

  3. 【Tarjan】洛谷P3379 Tarjan求LCA

    题目描述 如题,给定一棵有根多叉树,请求出指定两个点直接最近的公共祖先. 输入输出格式 输入格式: 第一行包含三个正整数N.M.S,分别表示树的结点个数.询问的个数和树根结点的序号. 接下来N-1行每 ...

  4. 【mp3】洗脑循环了!龙珠超 自在极意功 【究极の圣戦】串田アキラ 背景纯音乐

    自在极意功情况下发动自带bgm 曲名:究极の圣戦 首先是视频: http://dwz.cn/6Tj2Lq 然后是mp3:度盘下载>> 老外翻唱: 个人翻唱:全民k歌>>

  5. JavaSE(十一)之异常处理详解

    一.异常概述 在我们日常生活中,有时会出现各种各样的异常,例如:职工小王开车去上班,在正常情况下,小王会准时到达单位.但是天有不测风云,在小王去上班时,可能会遇到一些异常情况,比如小王的车子出了故障, ...

  6. HDU_5563Clarke and five-pointed star

    Clarke and five-pointed star Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K ( ...

  7. MIT公开课:算法导论 笔记(一)

    课程链接:http://open.163.com/special/opencourse/algorithms.html 第一课:算法分析基础 1.介绍插入排序与归并排序,计算并比较最坏运行时间 2.算 ...

  8. Spark性能调优之合理设置并行度

    Spark性能调优之合理设置并行度 1.Spark的并行度指的是什么?     spark作业中,各个stage的task的数量,也就代表了spark作业在各个阶段stage的并行度!     当分配 ...

  9. Spark性能调优之Shuffle调优

    Spark性能调优之Shuffle调优    • Spark底层shuffle的传输方式是使用netty传输,netty在进行网络传输的过程会申请堆外内存(netty是零拷贝),所以使用了堆外内存. ...

  10. git回退操作

    情况一:checkout 当你修改了某个文件,未提交暂存区,回退本次修改 git checkout -- file 情况三:reset 当你的代码,已提交到暂存区,还未提交到远程仓库 git log ...