POI生成WORD文档
h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child {
margin-top: 0;
padding-top: 0;
}
a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 {
margin-top: 0;
padding-top: 0;
}
h1+p, h2+p, h3+p, h4+p, h5+p, h6+p {
margin-top: 10px;
}
/* LINKS
=============================================================================*/
a {
color: #4183C4;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* LISTS
=============================================================================*/
ul, ol {
padding-left: 30px;
}
ul li > :first-child,
ol li > :first-child,
ul li ul:first-of-type,
ol li ol:first-of-type,
ul li ol:first-of-type,
ol li ul:first-of-type {
margin-top: 0px;
}
ul ul, ul ol, ol ol, ol ul {
margin-bottom: 0;
}
dl {
padding: 0;
}
dl dt {
font-size: 14px;
font-weight: bold;
font-style: italic;
padding: 0;
margin: 15px 0 5px;
}
dl dt:first-child {
padding: 0;
}
dl dt>:first-child {
margin-top: 0px;
}
dl dt>:last-child {
margin-bottom: 0px;
}
dl dd {
margin: 0 0 15px;
padding: 0 15px;
}
dl dd>:first-child {
margin-top: 0px;
}
dl dd>:last-child {
margin-bottom: 0px;
}
/* CODE
=============================================================================*/
pre, code, tt {
font-size: 12px;
font-family: Consolas, "Liberation Mono", Courier, monospace;
}
code, tt {
margin: 0 0px;
padding: 0px 0px;
white-space: nowrap;
border: 1px solid #eaeaea;
background-color: #f8f8f8;
border-radius: 3px;
}
pre>code {
margin: 0;
padding: 0;
white-space: pre;
border: none;
background: transparent;
}
pre {
background-color: #f8f8f8;
border: 1px solid #ccc;
font-size: 13px;
line-height: 19px;
overflow: auto;
padding: 6px 10px;
border-radius: 3px;
}
pre code, pre tt {
background-color: transparent;
border: none;
}
kbd {
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background-color: #DDDDDD;
background-image: linear-gradient(#F1F1F1, #DDDDDD);
background-repeat: repeat-x;
border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD;
border-image: none;
border-radius: 2px 2px 2px 2px;
border-style: solid;
border-width: 1px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
line-height: 10px;
padding: 1px 4px;
}
/* QUOTES
=============================================================================*/
blockquote {
border-left: 4px solid #DDD;
padding: 0 15px;
color: #777;
}
blockquote>:first-child {
margin-top: 0px;
}
blockquote>:last-child {
margin-bottom: 0px;
}
/* HORIZONTAL RULES
=============================================================================*/
hr {
clear: both;
margin: 15px 0;
height: 0px;
overflow: hidden;
border: none;
background: transparent;
border-bottom: 4px solid #ddd;
padding: 0;
}
/* TABLES
=============================================================================*/
/* IMAGES
=============================================================================*/
img {
max-width: 100%
}
-->
POI生成WORD文档
POI为Java系处理office文档的比较优秀的开源库,其中对于Excel的处理最为优秀,文档也写的很详细。不过很多网友都认为它在word文档处理方面就逊色很多,不过对于我本次的完成文档的生成我依然选择了POI。添加微信回复POI邀请你加群
需要完成功能
- 配置Word模板文件,包括表格
- 解析配置的Word文档,返回配置的特殊标记
- 构造数据,替换配置的标签,以及生成表格
配置word模版
采用${xx}方式配置标签,如果是表格在对应一行一列配置表格名称
注意在word文档中,如果两个相近的字符样式不同,word默认会保存在不同的RUN
元素中,由此很多朋友在配置好以后都需要保存为一个单独的文件,然后不把不在一起的标签合并到一个RUN
元素中,如果文件比较大,我相信这绝对是一个比较痛苦的事情,这里将会侧重处理这个问题.我的解决方案是只保留第一RUN
的样式其他的删掉
解析word模板
首先需要将文件转换为XWPFDocument
对象,可以通过流的当时,也可以通过opcpackage
,不过如果使用opcpackage
打开的方式,打开的文件和最终生成的文件不能够是同一个文件,我这里采用文件流的方式
public XWPFDocument openDocument() {
XWPFDocument xdoc = null;
InputStream is = null;
try {
is = new FileInputStream(saveFile);
xdoc = new XWPFDocument(is);
} catch (IOException e) {
e.printStackTrace();
}
return xdoc;
}
获取非列表的标签,实现方式XWPFDocument
对象有当前所有段落以及表格,这里暂不考虑表格嵌套表格的情况,每个段落的文本信息是可以通过p.getText()
获取,获取段落中文档配置信息如下:
// 获取段落集合中所有文本
public List<TagInfo> getWordTag(XWPFDocument doc, String regex) {
List<TagInfo> tags = new ArrayList<TagInfo>();
// 普通段落
List<XWPFParagraph> pars = doc.getParagraphs();
for (int i = 0; i < pars.size(); i++) {
XWPFParagraph p = pars.get(i);
setTagInfoList(tags, p, regex);
}
// Table中段落
List<XWPFTable> commTables = getDocTables(doc, false, regex);
for (XWPFTable table : commTables) {
List<XWPFParagraph> tparags = getTableParagraph(table);
for (int i = 0; i < tparags.size(); i++) {
XWPFParagraph p = tparags.get(i);
setTagInfoList(tags, p, regex);
}
}
return tags;
}
获取文本后通过正则解析,并依次保存到TagInfo中
// 向 taglist中添加新解析的段落信息
private void setTagInfoList(List<TagInfo> list, XWPFParagraph p,
String regex) {
if (regex == "")
regex = defaultRegex;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(p.getText());
int startPosition = 0;
while (matcher.find(startPosition)) {
String match = matcher.group();
if (!list.contains(new TagInfo(match, match, ""))) {
list.add(new TagInfo(match, match, ""));
}
startPosition = matcher.end();
}
}
解析表格
// 获取Table列表中的配置信息
public Map<String, List<List<TagInfo>>> getTableTag(XWPFDocument doc,
String regex) {
Map<String, List<List<TagInfo>>> mapList = new HashMap<String, List<List<TagInfo>>>();
List<XWPFTable> lstTables = getDocTables(doc, true, regex);
for (XWPFTable table : lstTables) {
// 获取每个表格第一个单元格,以及最后一行
String strTableName = getTableListName(table, regex);
List<List<TagInfo>> list = new ArrayList<List<TagInfo>>();
List<TagInfo> lstTag = new ArrayList<TagInfo>();
int rowSize = table.getRows().size();
XWPFTableRow lastRow = table.getRow(rowSize - 1);
for (XWPFTableCell cell : lastRow.getTableCells()) {
for (XWPFParagraph p : cell.getParagraphs()) {
// 去掉空白字符串
if (p.getText() != null && p.getText().length() > 0) {
setTagInfoList(lstTag, p, regex);
}
}
}
list.add(lstTag);
// 添加到数据集
mapList.put(strTableName, list);
}
return mapList;
}
生成WORD文档
难点替换标签
传入数据格式包含三个formtag以及一个tableTag
{"formTags":
[{"TagName":"${xxxx}","TagText":"${xxxx}","TagValue":""},
{"TagName":"${123}","TagText":"${123}","TagValue":""},
{"TagName":"${ddd}","TagText":"${ddd}","TagValue":""}],
"tableTags":{
"${table}":[
[{"TagName":"${COL1}","TagText":"${COL1}","TagValue":""},{"TagName":"${COL2}","TagText":"${COL2}","TagValue":""}]
]}
}
普通文档生成,并且保留配置样式,这里主要使用POI中提供searchText方法,返回Tag所有所在的RUN
标签,通过一个字符做比较,如果找的第一个匹配的文本开始计数,所有在当前条件下类型 $${xxx}这样的标签是无法实现替换的
替换普通文本Tag
public void ReplaceInParagraph(List<TagInfo> tagList, XWPFParagraph para,
String regex) {
if (regex == "")
regex = defaultRegex;
List<XWPFRun> runs = para.getRuns();
for (TagInfo ti : tagList) {
String find = ti.TagText;
String replValue = ti.TagValue;
TextSegement found = para.searchText(find,
new PositionInParagraph());
if (found != null) {
// 判断查找内容是否在同一个Run标签中
if (found.getBeginRun() == found.getEndRun()) {
XWPFRun run = runs.get(found.getBeginRun());
String runText = run.getText(run.getTextPosition());
String replaced = runText.replace(find, replValue);
run.setText(replaced, 0);
} else {
// 存在多个Run标签
StringBuilder sb = new StringBuilder();
for (int runPos = found.getBeginRun(); runPos <= found
.getEndRun(); runPos++) {
XWPFRun run = runs.get(runPos);
sb.append(run.getText((run.getTextPosition())));
}
String connectedRuns = sb.toString();
String replaced = connectedRuns.replace(find, replValue);
XWPFRun firstRun = runs.get(found.getBeginRun());
firstRun.setText(replaced, 0);
// 删除后边的run标签
for (int runPos = found.getBeginRun() + 1; runPos <= found
.getEndRun(); runPos++) {
// 清空其他标签内容
XWPFRun partNext = runs.get(runPos);
partNext.setText("", 0);
}
}
}
}
// 完成第一遍查找,检测段落中的标签是否已经替换完
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(para.getText());
boolean find = matcher.find();
if (find) {
ReplaceInParagraph(tagList, para, regex);
find = false;
}
}
表格主要是通过复制模版行,然后对模版行中的内容做修改
复制文本标签RUN
private void CopyRun(XWPFRun target, XWPFRun source) {
target.getCTR().setRPr(source.getCTR().getRPr());
// 设置文本
target.setText(source.text());
}
复制段落XWPFParagraph
private void copyParagraph(XWPFParagraph target, XWPFParagraph source) {
// 设置段落样式
target.getCTP().setPPr(source.getCTP().getPPr());
// 添加Run标签
for (int pos = 0; pos < target.getRuns().size(); pos++) {
target.removeRun(pos);
}
for (XWPFRun s : source.getRuns()) {
XWPFRun targetrun = target.createRun();
CopyRun(targetrun, s);
}
}
复制单元格XWPFTableCell
private void copyTableCell(XWPFTableCell target, XWPFTableCell source) {
// 列属性
target.getCTTc().setTcPr(source.getCTTc().getTcPr());
// 删除目标 targetCell 所有单元格
for (int pos = 0; pos < target.getParagraphs().size(); pos++) {
target.removeParagraph(pos);
}
// 添加段落
for (XWPFParagraph sp : source.getParagraphs()) {
XWPFParagraph targetP = target.addParagraph();
copyParagraph(targetP, sp);
}
}
复制行XWPFTableRow
private void CopytTableRow(XWPFTableRow target, XWPFTableRow source) {
// 复制样式
target.getCtRow().setTrPr(source.getCtRow().getTrPr());
// 复制单元格
for (int i = 0; i < target.getTableCells().size(); i++) {
copyTableCell(target.getCell(i), source.getCell(i));
}
}
以上就完成所有功能更,只要你配置规范,可以完全原样输出模版内容。这里特别感谢下肖哥哥大力支持。
其次,java的编码真的让人很无语,get或post时中文各种乱码
POI生成WORD文档的更多相关文章
- POI 生成 word 文档 简单版(包括文字、表格、图片、字体样式设置等)
POI 生成word 文档 一般有两种方法: ① word模板 生成word 文档 : ② 写代码直接生成 word 文档: 我这里演示的是第二种方法,即写代码生成 word文档,不多说废话,直接 ...
- POI生成word文档完整案例及讲解
一,网上的API讲解 其实POI的生成Word文档的规则就是先把获取到的数据转成xml格式的数据,然后通过xpath解析表单式的应用取值,判断等等,然后在把取到的值放到word文档中,最后在输出来. ...
- POI加dom4j将数据库的数据按一定格式生成word文档
一:需求:将从数据库查处来的数据,生成word文档,并有固定的格式.(dom4j的jar包+poi的jar包) 二:解决:(1)先建立固定格式的word文档(2007版本以上),另存成为xml文件,作 ...
- Java生成 Word文档的并打印解决方案
户要求用程序生成标准的word文档,要能打印,而且不能变形,以前用过很多解决方案,都在客户严格要求下牺牲的无比惨烈. POI读word文档还行,写文档实在不敢恭维,复杂的样式很难控制不提,想象一下一个 ...
- PoiDocxDemo【Android将表单数据生成Word文档的方案之二(基于Poi4.0.0),目前只能java生成】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 这个是<PoiDemo[Android将表单数据生成Word文档的方案之二(基于Poi4.0.0)]>的扩展,上一篇是根 ...
- PoiDemo【Android将表单数据生成Word文档的方案之二(基于Poi4.0.0)】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 使用Poi实现android中根据模板文件生成Word文档的功能.这里的模板文件是doc文件.如果模板文件是docx文件的话,请阅读 ...
- Android根据word模板文档将表单数据生成word文档的方案整理
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 尝试的方案包括以下几种: freemarker 只能在java项目上运行,无法在Android项目上运行: 参考资料:<Fre ...
- 使用FreeMarker生成word文档
生成word文档的框架比较多,比如poi,java2word,itext和freemarker. 调研之后,freemarker来实现挺简单的,具体步骤如下: 1. 新建word文档,占位符用${}, ...
- Java Web项目中使用Freemarker生成Word文档
Web项目中生成Word文档的操作屡见不鲜.基于Java的解决方式也是非常多的,包含使用Jacob.Apache POI.Java2Word.iText等各种方式,事实上在从Office 2003開始 ...
随机推荐
- 子进程 已安装 pre-removal 脚本 返回了错误号 1或2 与 子进程 已安装 post-installation 脚本 返回了错误号 1或2
今天在ubuntu kylin上安装了virtualbox, 后来我想删除了再装个新一点的,结果正常的情况下删除不了,我就把找到的virtualbox的目录全部都删除了, 再通过apt-get rem ...
- Win7 64位 VS2013环境使用cuda_7.5.18
首先得吐槽下VS2015出来快一年了CUDA居然还不支持,没办法重装系统刚从2013升到2015,还得再装回一个2013用,只为学习CUDA... 然后安装的时候,如果你选择自定义组件安装,注意不要改 ...
- viewpage滑动查看图片并再有缩略图预览
首先看下效果图, 主要功能分为3大块 一是滑动查看,通过viewpage来实现,方法见 http://www.cnblogs.com/lovemo1314/p/6109312.html 二.点击放大 ...
- JS-JQuery(JSONP)调用WebService跨域若干技术点
1.JSONP:JSON With Padding,让网页从别的网域获取信息,也就是跨域获取信息,可以当做是一种“工具”,大多数架构Jquery.EXTjs等都支持. 由于同源策略,一般来说位于 se ...
- MQL4程序:一个号称成功率100%的EA程序 .mq4
用mt4平台所提供的mql4语言编写.风险与利润同在,高风险可博得高利润.自己把握.已经测试通过,下 ...
- bdb log file 预设长度的性能优化
看代码随手记:log_put.c, __log_write() /* * If we're writing the first block in a log file on a filesystem ...
- QT
http://www.cnblogs.com/csulennon/p/4483711.html
- Amazon Resource Names (ARNs)
The following are the general formats for ARNs; the specific components and values used depend on th ...
- AndroidStudio学习笔记-第一个安卓程序
要带一个本科生做一部分跟安卓有点关系的项目,于是趁着机会学习一下编写安卓程序. 第一篇材料来自谷歌官方,传送门:https://developer.android.com/training/basic ...
- LINUX btmp 日志(lastb 命令)
Linux下/var/log/btmp文件: 今天查看了一下服务器,发现/var/log/btmp日志文件比较大,搜索一下,此文件是记录错误登录的日志,就是说有很多人试图使用密码字典登录ssh服务,此 ...