内容绝大部分来源于网络

准备工作


  • 准备【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. css3实现梯形三角

    近期移动端项目中,图片很多 移动端尽量少图片,以便提升加载速度!这时候css3可以大放光芒比如梯形的背景图 --------------------------------- ------------ ...

  2. SuperSocket入门(四)-命令行协议

         前面已经了解了supersocket的一些基本的属性及相关的方法,下面就进入重点的学习内容,通信协议.在没有看官方的文档之前,对于协议的理解首先想到的是TCP和UDP协议.TCP 和 UDP ...

  3. Java学习笔记8(面向对象一:概念、private)

    面向过程的思想:遇到问题,想,我该怎么解决这个问题?然后一步一步解决 面向对象的思想:遇到一件事的时候,思考,我该让谁来做,至于他怎样去做,不是我需要考虑的事情,只要最后做好就行 实际举例:我们要组装 ...

  4. Mvc项目部署IIS报错:没有为请求的URL配置默认文档,并且没有在服务器设置目录浏览

    问题原因: 1.iis是在安装完.net framework 之后才安装的,需要进行iis注册,开始--运行--cmd,打开命令行提示符,输入命令如下 C:\Windows\Microsoft.NET ...

  5. 【有上下界的网络流】ZOJ2341 Reactor Cooling(有上下界可行流)

     Description The terrorist group leaded by a well known international terrorist Ben Bladen is bulidi ...

  6. Redis 部署主从哨兵 C#使用,实现自动获取redis缓存 实例2

    资料查找https://www.cnblogs.com/tdws/p/5836122.html https://www.cnblogs.com/lori/p/5794454.html private ...

  7. jqueryui sortable拖拽后保存位置

    jqueryUI sortable 可以用来进行页面拖拽布局,然而有一个小问题就是拖拽后如何保存状态. 工作中遇到了这个情况,遍把这个问题记了下来,具体思路是: 利用拖拽stop后利用   var a ...

  8. 在webstorm开发微信小程序之使用阿里自定义字体图标

    1.下载阿里图标,解压出来之后有个.css文件 然后复制这css里面的所有代码 2.新建一个wxss文件,例如我新建的就是iconfont.wxss,然后把刚才复制的所有代码,复制到这个文件里面去. ...

  9. JS高级代码

    JS 的defineProperties 设置多个属性 var book = {}; //用Object.defineProperties()方法设置多个属性 Object.definePropert ...

  10. 大数据Hadoop学习之搭建Hadoop平台(2.1)

     关于大数据,一看就懂,一懂就懵. 一.简介 Hadoop的平台搭建,设置为三种搭建方式,第一种是"单节点安装",这种安装方式最为简单,但是并没有展示出Hadoop的技术优势,适合 ...