word变量替换含段和表格

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)