POI调用Word动态传参
2016-01-24 21:25
609 查看
功能描述
实现动态传参给Word模板,然后替换模板中的参数,最后生成目的文档;传入参数分别是源文件路径,目的文件路径和匹配MAP
2实现所需JAR包
poi-scratchpad-3.8-20120326.jar(文档最后有提供)3代码实现:
// 替换word中需要替换的特殊字符public static booleanreplaceWord(String srcPath,
String destPath,Map<String, String> map) {
String[] sp =srcPath.split("\\.");
String[] dp =destPath.split("\\.");
if ((sp.length > 0)&& (dp.length > 0)) {// 判断文件有无扩展名
// 比较文件扩展名
if (sp[sp.length -1].equalsIgnoreCase("docx")) {
try {
XWPFDocument document = new XWPFDocument(
POIXMLDocument.openPackage(srcPath));
// 替换段落中的指定文字
Iterator<XWPFParagraph> itPara = document
.getParagraphsIterator();
while(itPara.hasNext()) {
XWPFParagraph paragraph = (XWPFParagraph)itPara.next();
String str= paragraph.getText();
for(Map.Entry<String, String> entry : map
.entrySet()) {
str = str.replace(
entry.getKey(), entry.getValue());
}
List<XWPFRun> runs = paragraph.getRuns();
for(int i = 0; i < runs.size(); i++) {
if(runs.get(i)!=null){
runs.get(i).setText("",0); //将所有的XWPFRun都置空
}
if(i==0){
runs.get(i).setText(str,0); //将第一个XWPFRun的值存整个XWPFParagraph的字符串
}
}
}
// 替换表格中的指定文字
Iterator<XWPFTable> itTable = document.getTablesIterator();
while(itTable.hasNext()) {
XWPFTable table = (XWPFTable) itTable.next();
intrcount = table.getNumberOfRows();
for(int i = 0; i < rcount; i++) {
XWPFTableRow row = table.getRow(i);
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
String cellTextString = cell.getText();
for (Entry<String, String> e : map.entrySet()) {
if (cellTextString.contains(e.getKey()))
cellTextString = cellTextString
.replace(e.getKey(),
e.getValue());
}
cell.removeParagraph(0);
cell.setText(cellTextString);
}
}
}
FileOutputStream outStream = null;
outStream= new FileOutputStream(destPath);
document.write(outStream);
outStream.close();
returntrue;
} catch(Exception e) {
e.printStackTrace();
returnfalse;
}
} else
{
returnfalse;
}
} else {
return false;
}
}
调用参考如下:
String filepathString = "D:/2.docx";
String destpathString= "D:/2ttt.docx";
Map<String,String> map = new HashMap<String, String>();
map.put("${BANKNAME}", "中信");
map.put("${BANK}", "中信银行");
map.put("${TRANNAME}", "test");
map.put("${LAWYER}","test");
map.put("${YEAR}", "2015");
map.put("${MONTH}", "09");
map.put("${DAY}", "14");
System.out.println(replaceWord(filepathString,
destpathString, map)
4000
);
相关文章推荐
- 微软Word 2007数学插件 Microsoft Math 提供下载
- Office Word九条常用技巧
- C#实现简单合并word文档的方法
- powershell操作word详解
- C#生成Word文档代码示例
- 用vbscript把 Word 文档保存为文本文件的代码
- C#根据Word模版生成Word文件
- C#采用OpenXml给Word文档添加表格
- C#实现合并多个word文档的方法
- C#采用OpenXml给word里面插入图片
- C#使用Word中的内置对话框实例
- C#生成word记录实例解析
- VB调用Word拼写检查功能实例
- C# WORD操作实现代码
- 比较全的一个C#操作word文档示例
- C#添加、读取Word脚注尾注的方法
- jquery Moblie入门―hello world的示例代码学习
- asp.net中Word转Html的办法(不需要WORD组件)
- jsp实现针对excel及word文档的打印方法
- 在office Word中任意选中单词某一部分字母