`
yuky1327
  • 浏览: 123257 次
  • 性别: Icon_minigender_2
  • 来自: 广州
社区版块
存档分类
最新评论

word变量替换含段和表格

    博客分类:
  • Java
 
阅读更多
package jeecg.kxcomm.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.transaction.SystemException;

import jeecg.kxcomm.entity.systemmanager.TbContractDocVariableEntity;
import jeecg.kxcomm.entity.systemmanager.TbContractTemplatesDocVariableEntity;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;


/**
*
* 操作word文档查找替换
*
* @author zhangjh 新增日期:2012-12-19
* @since ContractManage
*/
public class WordTools {
private static WordTools instance = null;
Logger log = Logger.getLogger(WordTools.class);
private WordTools(){

}

public static WordTools getInstance(){
if(instance == null)
instance = new WordTools();

return instance;
}

public static WordTools getNewInstance(){
return new WordTools();
}

/**
*
* 替换word中的变量并导出.docx
*
* @param templatesDoc
* @param docVariable
* @param exportDoc
* @return
* @author zhangjh 新增日期:2012-12-20
* @since ContractManage
*/
public boolean export(String templatesDoc,List<TbContractDocVariableEntity> docVariable,String exportDoc ){
File bfile = null;
XWPFDocument doc = null;
File file = null;
FileOutputStream fos = null;
OPCPackage pack  = null;
String fileTempPath = PathConstants.CurrentDirectory +"/"+PathConstants.ExportContractPath;
File fileTemp = new File(fileTempPath);
//System.out.println("新建临时文件:"+fileTempPath);
if(!fileTemp.exists()){
fileTemp.mkdirs();
}
fileTempPath += "/temp_"+System.currentTimeMillis()+".docx";
fileTemp = new File(fileTempPath);
try {
log.info("==================================================templatesDoc:"+templatesDoc+",exportDoc:"+exportDoc);
bfile = new File(templatesDoc);
if(!bfile.exists()){
throw new SystemException("合同模版文件不存在,请检查"+templatesDoc+"是否存在");
}
file = new File(exportDoc);
if(file.exists()){
file.delete();
}

org.apache.commons.io.FileUtils.copyFile(bfile, fileTemp);
System.out.println("拷贝模板到临时文件中:templatesDoc->"+templatesDoc+"\n ,fileTemmpPath:"+fileTempPath);

pack = POIXMLDocument.openPackage(fileTempPath);
doc = new XWPFDocument(pack);
//把word中的文章段替换变量
List<XWPFParagraph> paragraphs = doc.getParagraphs();
for (XWPFParagraph tmp : paragraphs) {
List<XWPFRun> runs = tmp.getRuns();
for (XWPFRun aa : runs) {
if(aa.getText(0)==null||"".equals(aa.getText(0)))
continue;
String docText = aa.getText(0)!=null?aa.getText(0).trim():null;

for(TbContractDocVariableEntity var:docVariable){
if (var.getVariablename().equals(docText)) {
log.info("段找到匹配:文档内容->"+docText+",变量名称->"+var.getVariablename());
System.out.println("段找到匹配:文档内容->"+docText+",变量名称->"+var.getVariablename());
aa.setText(var.getContent(), 0);
}
}
}
}
//把word中的表格段替换变量
List<XWPFTable> tables = doc.getTables();
for (XWPFTable table : tables) {
int rcount = table.getNumberOfRows();
for(int i=0;i<rcount;i++){
XWPFTableRow row = table.getRow(i);
List<XWPFTableCell> cells= row.getTableCells();
for(int j=0;j<cells.size();j++){
XWPFTableCell c = cells.get(j);
List<IBodyElement> el =  c.getBodyElements();
for(int h=0;h<el.size();h++){
XWPFParagraph p = (XWPFParagraph) el.get(h);
//System.out.println("XWPFParagraph:"+p.getText());
List<XWPFRun> runs = p.getRuns();
for (XWPFRun aa : runs) {
if(aa.getText(0)==null||"".equals(aa.getText(0)))
continue;
String docText = aa.getText(0)!=null?aa.getText(0).trim():null;
for(TbContractDocVariableEntity var:docVariable){
if (var.getVariablename().equals(docText)) {
log.info("表格找到匹配:文档内容->"+docText+",变量名称->"+var.getVariablename());
System.out.println("表格找到匹配:文档内容->"+docText+",变量名称->"+var.getVariablename());
aa.setText(var.getContent(), 0);
}
}
}
}
}
}
}

fos = new FileOutputStream(exportDoc);
doc.write(fos);
System.out.println("把替换的变量保存到最终文件:"+exportDoc);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(bfile!=null){
bfile = null;
}
if(doc!=null){
doc = null;
}
if(file!=null){
file = null;
}
if(pack!=null){
pack.flush();
try {
pack.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fileTemp!=null){
fileTemp.delete();
}
}
return true;
}

/**
*
* 返回word中有效的变量
*
* @param templatesDoc
* @param docVariable
* @return
* @author zhangjh 新增日期:2012-12-20
* @since ContractManage
*/
public HashMap<String, TbContractTemplatesDocVariableEntity> checkVariable(String templatesDoc,List<TbContractTemplatesDocVariableEntity> docVariable){
HashMap<String, TbContractTemplatesDocVariableEntity> map = new HashMap<String, TbContractTemplatesDocVariableEntity>();
try {
OPCPackage pack = POIXMLDocument.openPackage(templatesDoc);
XWPFDocument doc = new XWPFDocument(pack);
List<XWPFParagraph> paragraphs = doc.getParagraphs();
for (XWPFParagraph tmp : paragraphs) {
List<XWPFRun> runs = tmp.getRuns();
for (XWPFRun aa : runs) {
for(TbContractTemplatesDocVariableEntity var:docVariable){
if (var.getVariablename().equals(aa.getText(0))) {
map.put(var.getVariablename(), var);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}

/**
*
* 方法用途和描述: 文件移动
* @param string  文件存在地址
* @param string2   文件需要保存的地址
* @author chenliang 新增日期:2013-1-11
* @since ContractManage
*/
public void moveFile(String string, String string2) {
try {
File uploadFile = new File(string);
if(uploadFile.exists() && uploadFile.isFile()){
File downPath = new File(string2);
FileUtils.copyFile(uploadFile, downPath);
}
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
PathConstants.CurrentDirectory  = "E://tmp//";
WordTools tools =WordTools.getInstance();
List<TbContractDocVariableEntity> docVariable = new ArrayList();
TbContractDocVariableEntity var=new TbContractDocVariableEntity();
var.setVariablename("$CNUMBER");
var.setContent("AAAAAAA");
docVariable.add(var);//
var=new TbContractDocVariableEntity();
var.setVariablename("$NAME");
var.setContent("BBBBBB");
docVariable.add(var);
try {
tools.export("E://tmp//1407913488149.docx",docVariable, "E://tmp//aa.docx");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
分享到:
评论

相关推荐

    word文档模板-使用poi技术替换文档中的变量

    给出Java-poi导出Word时,所需的Word模板。 注意:1,word模板中的表格单元格只能有唯一的变量。(如需多个变量,可以在word中隐藏表格来实现。) 2,word模板中变量前后不能有空格。

    Apache poi 根据word模板生成word报表 替换 循环列表 图片

    Apache poi 根据word模板生成word报表 替换 循环列表 图片,代码调试过了,修改相应的图片位置,word模板路径即可运行

    .net 按照word模板替换制定内容 含图片 保留格式不变

    .net 按照word模板替换制定内容,含图片,保留格式不变,附件是代码 可以直接使用,测试通过,如果不能运行 可以安装Office组件

    poi-tl引擎实现world模板内容替换(支持docx)

    * poi-tl引擎实现world模板内容替换(支持docx) * 依赖poi-tl,commons-lang3, poi-ooxml-schemas, poi-ooxml, poi,slf4j

    WordExportUtls.java

    可以对word中的文本域的变量进行替换,可以对表格中的变量进行替换,可以对文本框中的变量进行替换,可以更新目录。注(图片部分未完成)

    WordExportUtll.java

    可以替换word文本中的变量(说明用特殊符号区分),可以替换表格中的变量,可以替换文本框中的变量,图片部分替换不了所需用的jar包 &lt;groupId&gt;org.apache.poi &lt;artifactId&gt;poi &lt;version&gt;3.13 &lt;groupId&gt;org....

    ACReport中国式报表组件2010(Ver2.2)(含文档)

    三、 增加宏替换功能(宏变量)的支持【设计器】 四、 增加IAcFuncionLib接口支持,以一种新的方式扩充函数库【SDK】 五、 增加LoadFromStream和SaveToStream方法及IAcNetStream接口支持【SDK】 六、 修改了单元格...

    ACReport中国式报表控件2010(Ver2.25)

    三、 增加宏替换功能(宏变量)的支持【设计器】 四、 增加IAcFuncionLib接口支持,以一种新的方式扩充函数库【SDK】 五、 增加LoadFromStream和SaveToStream方法及IAcNetStream接口支持【SDK】 六、 修改了单元格...

    oracle学习文档 笔记 全面 深刻 详细 通俗易懂 doc word格式 清晰 连接字符串

    oracle学习文档 笔记 全面 深刻 详细 通俗易懂 doc word格式 清晰 第一章 Oracle入门 一、 数据库概述 数据库(Database)是按照数据结构来组织、存储和管理数据的仓库,它产生于距今五十年前。简单来说是本身可视...

    Excel2007图表完全剖析 3/8

    12.1 在PowerPoint或Word中显示Excel图表 279 12.1.1 将图表复制为链接到原工作簿链接的动态图表 280 12.1.2 将图表复制为与原工作簿拷贝链接的动态图表 281 12.1.3 将图表复制为图形 282 12.1.4 将图表...

    《程序天下:JavaScript实例自学手册》光盘源码

    3.46 查找两段文本中相同的词句 3.47 自动保存网页输出的文本 3.48 文本编辑器 第4章 鼠标特效 4.1 禁用鼠标右键 4.2 使鼠标滚轮失效 4.3 状态栏显示鼠标位置 4.4 点击鼠标右键到指定页 4.5 鼠标放到图片上会显示...

    程序天下:JavaScript实例自学手册

    3.46 查找两段文本中相同的词句 3.47 自动保存网页输出的文本 3.48 文本编辑器 第4章 鼠标特效 4.1 禁用鼠标右键 4.2 使鼠标滚轮失效 4.3 状态栏显示鼠标位置 4.4 点击鼠标右键到指定页 4.5 鼠标放到图片上会显示...

    freemarker总结

    指定默认值时,并不要求默认值的类型和变量类型相同.使用??运算符非常简单,它总是返回一个布尔值,用法为:variable??,如果该变量存在,返回true,否则返回false ########################### 最常用的概念 1、 scalars...

    Vim用户手册中文版72.pdf

    12.1 替换一个word 12.2 将Last,First为First Last 12.3 排序 12.4 反转行序 12.5 统计字数 12.6 查找帮助页 12.7 消除多余空格 12.8 查找一个word在何处被引用 第20章 回事冒号命令 20.1 命令行编辑 20.2 命令行...

    PhraseExpress v14.0.139d.zip

    软件可以将经常输入的文本或语句通过热键或设定的自动文本直接输入(Autotext/热字符串替换),有效减少工作量,提高录入准确度,可以很大程度上提高输入效率,此外,软件还提供了强大的宏功能,可以将动态文本添加...

    Excel2007图表完全剖析 8/8

    12.1 在PowerPoint或Word中显示Excel图表 279 12.1.1 将图表复制为链接到原工作簿链接的动态图表 280 12.1.2 将图表复制为与原工作簿拷贝链接的动态图表 281 12.1.3 将图表复制为图形 282 12.1.4 将图表...

    Excel2007图表完全剖析 1/8

    12.1 在PowerPoint或Word中显示Excel图表 279 12.1.1 将图表复制为链接到原工作簿链接的动态图表 280 12.1.2 将图表复制为与原工作簿拷贝链接的动态图表 281 12.1.3 将图表复制为图形 282 12.1.4 将图表...

    Excel2007图表完全剖析 2/8

    12.1 在PowerPoint或Word中显示Excel图表 279 12.1.1 将图表复制为链接到原工作簿链接的动态图表 280 12.1.2 将图表复制为与原工作簿拷贝链接的动态图表 281 12.1.3 将图表复制为图形 282 12.1.4 将图表...

Global site tag (gtag.js) - Google Analytics