数据导出生成word附件使用POI的XWPFTemplate对象
比较常用的实现Java导入、导出Excel的技术有两种Jakarta POI和Java Excel。
Jakarta POI 是一套用于访问微软格式文档的Java API。Jakarta POI有很多组件组成,其中有用于
操作Excel格式文件的HSSF和
用于操作Word的HWPF;

一、前端使用get请求和post请求都可以
get请求:
window.location.href= appPath+"/export/handoverForm?ticketId="+self.ticketId +
"&complainId="+row.id+"&formCode="+self.exportFormCode.complainDetail;
隐藏form表单改写成post请求,form表单get和post都可以:
<form id="exportForm" action="/service/xfComplain/exportCaseLedger" method="post">
<input type="hidden" name="dataRange" id="dataRange"/>
<input type="hidden" name="processStatus" id="processStatus"/>
<input type="hidden" name="cantonCode" id="cantonCode"/>
<input type="hidden" name="startDate" id="startDate"/>
<input type="hidden" name="endDate" id="endDate"/>
<input type="hidden" name="multiFildMatch" id="multiFildMatch"/>
</form>
$("#dataRange").val(self.table.pageData.dataRange);
$("#processStatus").val(self.table.pageData.processStatus);
$("#startDate").val(self.table.pageData.startDate);
$("#endDate").val(self.table.pageData.endDate);
$("#multiFildMatch").val(self.table.pageData.multiFildMatch);
$('#exportForm').submit();
二、java代码
@ResponseBody
@RequestMapping("/exportWord")
public void exportHandoverForm(HttpServletRequest request,
HttpServletResponse response, ExportParam exportParam) {
String projectPath = getProjectPath(request);
String templateFile = getTemplateFile(exportParam, projectPath, request);
Map<String, Object> data = new HashMap<>();
File file = null;
InputStream in = null;
ServletOutputStream out = null;
try {
// 数据源
HandoverModel handoverModel = getHandoverFormData(exportParam.getComplainId());
// 反射机制,获取所有属性对象,在拿到属性值,设置数据
for (Field field : HandoverModel.class.getDeclaredFields()) {
// 暴力反射,不是public修饰的属性也要获取
field.setAccessible(true);
data.put(field.getName(), field.get(handoverModel));
}
// 数据源组成map键值对形式
data.put("reportorList", handoverModel.getReportorList().getDatas());
String fileName = handoverModel.getCaseCode();
String exportFilePath = projectPath + ExportConstant.DEFAULT_EXPORT_PATH;
logger.info("----------templateFile:" + templateFile);
logger.info("-----------projectPath:" + projectPath);
// Configure对象是处理表格数据,可以自适应生成对应行数数据
Configure config = Configure.newBuilder().customPolicy("reportorList", new FileTablePolicy()).build();
// XWPFTemplate对象是处理word文档对象,根据map数据源的键值对渲染文档数据
XWPFTemplate template = XWPFTemplate.compile(templateFile, config).render(data);
// 文件生成到本地,先生成好文档,再读取到内存中响应给前台
String downloadFileName = fileName + ".docx";
File outPutFile = new File(exportFilePath);
if (!outPutFile.exists()) {
outPutFile.mkdirs();
}
FileOutputStream outFile = new FileOutputStream(exportFilePath + downloadFileName);
template.write(outFile);
outFile.flush();
outFile.close();
template.close();
// 通过文件流读取到文件,再将文件通过response的输出流,返回给页面下载
file = new File(projectPath + ExportConstant.DEFAULT_EXPORT_PATH + downloadFileName);
in = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(downloadFileName, "UTF-8"))));
out = response.getOutputStream();
byte[] buffer = new byte[512];
int bytesToRead = -1;
// 用响应对象response中的输出流读取生成好的文件
while ((bytesToRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch (Exception e) {
logger.error("导出word出错", e);
} finally {
if (in != null) try {
in.close();
if (out != null) out.close();
if (file != null) file.delete(); // 删除临时文件
} catch (IOException e) {
logger.error("删除删除临时文件出错", e);
}
}
}
使用XWPFTemplate引擎,插件化Configure插入表格;

三、不需要插入表格:

XWPFTemplate template = XWPFTemplate.compile(templateFile).render(data);
数据导出生成word附件使用POI的XWPFTemplate对象的更多相关文章
- 数据导出生成Excel附件使用POI的HSSFWorkbook对象
比较常用的实现Java导入.导出Excel的技术有两种Jakarta POI和Java Excel.Jakarta POI 是一套用于访问微软格式文档的Java API.Jakarta POI有很多组 ...
- PowerDesigner将PDM导出生成WORD文档
PowerDesigner将PDM导出生成WORD文档 环境 PowerDesigner15 1.点击Report Temlates 制作模板 2.如果没有模板,单击New图标创建.有直接双击进入. ...
- 在ASP.NET中将GridView数据导出到Word、Excel
在ASP.NET中将GridView数据导出到Word.Excel asp.net,导出gridview数据到Word,Excel,PDF #region Export to Word, Exce ...
- 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的 ...
- 实现excel导入导出功能,excel导入数据到页面中,页面数据导出生成excel文件
今天接到项目中的一个功能,要实现excel的导入,导出功能.这个看起来思路比较清楚,但是做起了就遇到了不少问题. 不过核心的问题,大家也不会遇到了.每个项目前台页面,以及数据填充方式都不一样,不过大多 ...
- gridview数据导出到word和excel以及excel的导入
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI ...
- 使用NPOI将数据导出为word格式里的table
开发环境:VS2013+MySQL5.5+EF6+NPOI2.0.6 格式:WinForm+CodeFirst PS:vs2013的CodeFirst很方便了啊 CodeFirst方式就不再赘述了. ...
- 将HTML导出生成word文档
前言: 项目开发中遇到了需要将HTML页面的内容导出为一个word文档,所以有了这边随笔. 当然,项目开发又时间有点紧迫,第一时间想到的是用插件,所以百度了下.下面就介绍两个导出word文档的方法. ...
随机推荐
- RHCE_DAY05
cron周期性计划任务 cron周期性计划任务用来定期执行程序,目前最主要的用途是定期备份数据 软件包名:cronie.crontabs 服务名:crond 日志文件:/var/log/cron cr ...
- gRPC学习之二:GO的gRPC开发环境准备
欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos gRPC学习系列文章链接 在CentOS7部署和设置G ...
- 启动Eclipse时,弹出JVM terminated. Exit code=127..错误的解决方案
在Linux环境下,启动Eclipse,会弹出并报如下的错误,且不能启动该工具 JVM terminated. Exit code=127/eclipse/jdk1.7.0_71/bin/java-D ...
- 第6篇-Java方法新栈帧的创建
在 第2篇-JVM虚拟机这样来调用Java主类的main()方法 介绍JavaCalls::call_helper()函数的实现时提到过如下一句代码: address entry_point = me ...
- Redis如何实现分布式锁
今天我们来聊一聊分布式锁的那些事. 相信大家对锁已经不陌生了,我们在多线程环境中,如果需要对同一个资源进行操作,为了避免数据不一致,我们需要在操作共享资源之前进行加锁操作.在计算机科学中,锁(lock ...
- 数据结构与算法-排序(九)基数排序(Radix Sort)
摘要 基数排序是进行整数序列的排序,它是将整数从个位开始,直到最大数的最后一位截止,每一个进位(比如个位.十位.百位)的数进行排序比较. 每个进位做的排序比较是用计数排序的方式处理,所以基数排序离不开 ...
- C#10在List, Queue 以及Stack中使用EnsureCapacity方法来提升性能
简介 在今天的文章中,我们将介绍 C# 10 中引入的一项新功能.这是已添加到 List.Queue 和 Stack 集合中的 EnsureCapacity 方法.我们将讨论为什么我们应该使用这个方法 ...
- nodejs 更改项目端口号的 方法
我这里是 koa2 项目 1.项目目录 serverConf.js 这里面配置端口 代码如下: const ServerConf= { ServicePort: 3036 }; module.expo ...
- GPRS RTU设备OPC Server接口C# 实现
通过本OPC Server程序接口可为用户提供以OPC标准接口访问远程GPRS/3G/以太网 RTU设备实时数据的方式.从而方便实现GPRS/3G/以太网 RTU设备与组态软件或DCS系统的对接.本程 ...
- 获取sim 卡的IMEI 和 IMSI
IReadOnlyList<string> networkAccIds = Windows.Networking.NetworkOperators.MobileBroadbandAccou ...