java 读取word模板文件路径_Java 读取Word模板替换内容并另存
用到的工具:jacob-1.17-M2.zip,文件解压后主要有三个文件:jacob.jar、jacob-1.17-M2-x64.dll和jacob-1.17-M2-x86.dll。
jacob.jar引入到项目工程中,jacob-1.17-M2-x64.dll放在C:\Windows\System32下,如果系统是32位的则把jacob-1.17-M2-x86.dll放在C:\Windows\System32下。
注意:文件名要用.doc,万不能用.docx。那样会打不开文件
代码示例:
/*
* Java2word.java
*
* Created on 2007年8月13日, 上午10:32
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
/*
* 传入数据为HashMap对象,对象中的Key代表word模板中要替换的字段,Value代表用来替换的值。
* word模板中所有要替换的字段(即HashMap中的Key)以特殊字符开头和结尾,如:$code$、$date$……,
以免执行错误的替换。
* 所有要替换为图片的字段,Key中需包含image或者Value为图片的全路径(目前只判断文件后缀名为:.bmp、
.jpg、.gif)。
* 要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中:R代表从表格的第R行开始替换,N代表
word模板中的第N张表格;Value为ArrayList对象,ArrayList中包含的对象统一为String[],一条String[]代
表一行数据,ArrayList中第一条记录为特殊记录,记录的是表格中要替换的列号,如:要替换第一列、第三列、
第五列的数据,则第一条记录为String[3] {“1”,”3”,”5”}。
*/
package yz;
/**
*
* @author kdl
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class Java2word {
private boolean saveOnExit;
/**
* word文档
*/
Dispatch doc = null;
/**
* word运行程序对象s
*/
private ActiveXComponent word;
/**
* 所有word文档
*/
private Dispatch documents;
/**
* 构造函数
*/
public Java2word() {
if(word==null){
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible",new Variant(false));
}
if(documents==null)
documents = word.getProperty("Documents").toDispatch();
saveOnExit = false;
}
/**
* 设置参数:退出时是否保存
* @param saveOnExit boolean true-退出时保存文件,false-退出时不保存文件
*/
public void setSaveOnExit(boolean saveOnExit) {
this.saveOnExit = saveOnExit;
}
/**
* 得到参数:退出时是否保存
* @return boolean true-退出时保存文件,false-退出时不保存文件
*/
public boolean getSaveOnExit() {
return saveOnExit;
}
/**
* 打开文件
* @param inputDoc String 要打开的文件,全路径
* @return Dispatch 打开的文件
*/
public Dispatch open(String inputDoc) {
return Dispatch.call(documents,"Open",inputDoc).toDispatch();
//return Dispatch.invoke(documents,"Open",Dispatch.Method,new Object[]{inputDoc},new int[1]).toDispatch();
}
/**
* 选定内容
* @return Dispatch 选定的范围或插入点
*/
public Dispatch select() {
return word.getProperty("Selection").toDispatch();
}
/**
* 把选定内容或插入点向上移动
* @param selection Dispatch 要移动的内容
* @param count int 移动的距离
*/
public void moveUp(Dispatch selection,int count) {
for(int i = 0;i < count;i ++)
Dispatch.call(selection,"MoveUp");
}
/**
* 把选定内容或插入点向下移动
* @param selection Dispatch 要移动的内容
* @param count int 移动的距离
*/
public void moveDown(Dispatch selection,int count) {
for(int i = 0;i < count;i ++)
Dispatch.call(selection,"MoveDown");
}
/**
* 把选定内容或插入点向左移动
* @param selection Dispatch 要移动的内容
* @param count int 移动的距离
*/
public void moveLeft(Dispatch selection,int count) {
for(int i = 0;i < count;i ++) {
Dispatch.call(selection,"MoveLeft");
}
}
/**
* 把选定内容或插入点向右移动
* @param selection Dispatch 要移动的内容
* @param count int 移动的距离
*/
public void moveRight(Dispatch selection,int count) {
for(int i = 0;i < count;i ++)
Dispatch.call(selection,"MoveRight");
}
/**
* 把插入点移动到文件首位置
* @param selection Dispatch 插入点
*/
public void moveStart(Dispatch selection) {
Dispatch.call(selection,"HomeKey",new Variant(6));
}
/**
* 从选定内容或插入点开始查找文本
* @param selection Dispatch 选定内容
* @param toFindText String 要查找的文本
* @return boolean true-查找到并选中该文本,false-未查找到文本
*/
public boolean find(Dispatch selection,String toFindText) {
//从selection所在位置开始查询
Dispatch find = word.call(selection,"Find").toDispatch();
//设置要查找的内容
Dispatch.put(find,"Text",toFindText);
//向前查找
Dispatch.put(find,"Forward","True");
//设置格式
Dispatch.put(find,"Format","True");
//大小写匹配
Dispatch.put(find,"MatchCase","True");
//全字匹配
Dispatch.put(find,"MatchWholeWord","True");
//查找并选中
return Dispatch.call(find,"Execute").getBoolean();
}
/**
* 把选定内容替换为设定文本
* @param selection Dispatch 选定内容
* @param newText String 替换为文本
*/
public void replace(Dispatch selection,String newText) {
//设置替换文本
Dispatch.put(selection,"Text",newText);
}
/**
* 全局替换
* @param selection Dispatch 选定内容或起始插入点
* @param oldText String 要替换的文本
* @param newText String 替换为文本
*/
public void replaceAll(Dispatch selection,String oldText,Object replaceObj) {
//移动到文件开头
moveStart(selection);
if(oldText.startsWith("table") || replaceObj instanceof ArrayList)
replaceTable(selection,oldText,(ArrayList) replaceObj);
else {
String newText = (String) replaceObj;
if(newText==null)
newText="";
if(oldText.indexOf("image") != -1&!newText.trim().equals("") || newText.lastIndexOf(".bmp") != -1 || newText.lastIndexOf(".jpg") != -1 || newText.lastIndexOf(".gif") != -1){
while(find(selection,oldText)) {
replaceImage(selection,newText);
Dispatch.call(selection,"MoveRight");
}
}else{
while(find(selection,oldText)) {
replace(selection,newText);
Dispatch.call(selection,"MoveRight");
}
}
}
}
/**
* 替换图片
* @param selection Dispatch 图片的插入点
* @param imagePath String 图片文件(全路径)
*/
public void replaceImage(Dispatch selection,String imagePath) {
Dispatch.call(Dispatch.get(selection,"InLineShapes").toDispatch(),"AddPicture",imagePath);
}
/**
* 替换表格
* @param selection Dispatch 插入点
* @param tableName String 表格名称,形如table$1@1、table$2@1...table$R@N,R代表从表格中的第N行开始填充,N代表word文件中的第N张表
* @param fields HashMap 表格中要替换的字段与数据的对应表
*/
public void replaceTable(Dispatch selection,String tableName,ArrayList dataList) {
if(dataList.size() <= 1) {
System.out.println("Empty table!");
return;
}
//要填充的列
String[] cols = (String[]) dataList.get(0);
//表格序号
String tbIndex = tableName.substring(tableName.lastIndexOf("@") + 1);
//从第几行开始填充
int fromRow = Integer.parseInt(tableName.substring(tableName.lastIndexOf("$") + 1,tableName.lastIndexOf("@")));
//所有表格
Dispatch tables = Dispatch.get(doc,"Tables").toDispatch();
//要填充的表格
Dispatch table = Dispatch.call(tables,"Item",new Variant(tbIndex)).toDispatch();
//表格的所有行
Dispatch rows = Dispatch.get(table,"Rows").toDispatch();
//填充表格
for(int i = 1;i < dataList.size();i ++) {
//某一行数据
String[] datas = (String[]) dataList.get(i);
//在表格中添加一行
if(Dispatch.get(rows,"Count").getInt() < fromRow + i - 1)
Dispatch.call(rows,"Add");
//填充该行的相关列
for(int j = 0;j < datas.length;j ++) {
//得到单元格
Dispatch cell = Dispatch.call(table,"Cell",Integer.toString(fromRow + i - 1),cols[j]).toDispatch();
//选中单元格
Dispatch.call(cell,"Select");
//设置格式
Dispatch font = Dispatch.get(selection,"Font").toDispatch();
Dispatch.put(font,"Bold","0");
Dispatch.put(font,"Italic","0");
//输入数据
Dispatch.put(selection,"Text",datas[j]);
}
}
}
/**
* 保存文件
* @param outputPath String 输出文件(包含路径)
*/
public void save(String outputPath) {
Dispatch.call(Dispatch.call(word,"WordBasic").getDispatch(),"FileSaveAs",outputPath);
}
/**
* 关闭文件
* @param document Dispatch 要关闭的文件
*/
public void close(Dispatch doc) {
Dispatch.call(doc,"Close",new Variant(saveOnExit));
word.invoke("Quit",new Variant[]{});
word = null;
}
/**
* 根据模板、数据生成word文件
* @param inputPath String 模板文件(包含路径)
* @param outPath String 输出文件(包含路径)
* @param data HashMap 数据包(包含要填充的字段、对应的数据)
*/
public void toWord(String inputPath,String outPath,HashMap data) {
String oldText;
Object newValue;
try {
if(doc==null)
doc = open(inputPath);
Dispatch selection = select();
Iterator keys = data.keySet().iterator();
while(keys.hasNext()) {
oldText = (String) keys.next();
newValue = data.get(oldText);
replaceAll(selection,oldText,newValue);
}
save(outPath);
} catch(Exception e) {
System.out.println("操作word文件失败!");
e.printStackTrace();
} finally {
if(doc != null)
close(doc);
}
}
public synchronized static void word(String inputPath,String outPath,HashMap data){
Java2word j2w = new Java2word();
j2w.toWord(inputPath,outPath,data);
}
public static void main(String[] args) {
HashMap data = new HashMap();
data.put("$code$","2007-8-1");
data.put("$date$","2007-8-2");
data.put("$img$","E:\\资料\\1.jpg");
/*
ArrayList table = new ArrayList(3);
String[] fieldName = {"1","3","5"};
table.add(fieldName);
String[] field1 = {"1","751002","华夏证券"};
table.add(field1);
String[] field2 = {"2","751004","国泰君安"};
table.add(field2);
String[] field3 = {"3","751005","海通证券"};
table.add(field3);
data.put("table$3@2",table);
ArrayList table1 = new ArrayList(3);
String[] fieldName1 = {"1","2","3"};
table1.add(fieldName1);
String[] field11 = {"1","751002","华夏证券"};
table1.add(field11);
String[] field21 = {"2","751004","国泰君安"};
table1.add(field21);
String[] field31 = {"3","751005","海通证券"};
table1.add(field31);
data.put("table$2@1",table1);
*/
Java2word j2w = new Java2word();
long time1 = System.currentTimeMillis();
j2w.toWord("E:\\资料\\Template.doc","E:\\资料\\result.doc",data);
System.out.println("time cost : " + (System.currentTimeMillis() - time1));
}
}
java 读取word模板文件路径_Java 读取Word模板替换内容并另存相关推荐
- java读取src xml文件路径_Java获取路径方法相对路径读取xml文件方法
(1).request.getRealPath("/");//不推荐使用获取工程的根路径 (2).request.getRealPath(request.getRequestURI ...
- java加载声音文件类型_java读取各种类型文件
用到的几个包 bcmail-jdk14-132.jar/bcprov-jdk14-132.jar/checkstyle-all-4.2.jar/FontBox-0.1.0-dev.jar/lucene ...
- java file类复制文件路径_java进阶(34)--File类、目录复制
一.File类的理解 1.File类不能完成文件的读与写. 2.FIle类代表:文件或目录的路径名的抽象表示形式. 二.FIle类常用方法: 1.创建一个FIle对象:File() File f1=n ...
- java log输出到文件路径_Java - 配置log4j的日志文件路径 (附-获取当前类路径的多种方法)...
1 日志路径带来的痛点 Java 项目中少不了要和log4j等日志框架打交道, 开发环境和生产环境下日志文件的输出路径总是不一致, 设置为绝对路径的方式缺少了灵活性, 每次变更项目路径都要修改文件, ...
- java获取上传文件路径_java上传文件获取跟目录的办法
在java中获得文件的路径在我们做上传文件操作时是不可避免的. web 上运行 1: this.getClass().getClassLoader().getResource("/" ...
- java读取文件 路径_Java中的获取文件的物理绝对路径,和读取文件
获取文件的绝对路径,读取该文件 一.文件目录打印图 下面的文件目录图,是项目中文件的位置信息:下面的例子是按照这个图来演示的. . |-- java | |-- ibard | | |-- demo1 ...
- java word模板poi生成文件_利用poi读取word模板文件生成新的word文档
利用poi读取word模板文件生成新的word文档 利用poi读取word模板文件,并回填逻辑数据,生成并导出需要的word文档源码.解决模板读取异常问题,提供wordUtils工具类(各种功能实现) ...
- 利用poi读取word模板文件生成新的word文档
利用poi读取word模板文件生成新的word文档 利用poi读取word模板文件,并回填逻辑数据,生成并导出需要的word文档源码.解决模板读取异常问题,提供wordUtils工具类(各种功能实现) ...
- 用Python读取文件名和文件路径
用Python读取文件名和文件路径 文件名 无限制 有限制 文件路径 无限制 有限制 实战 文件结构 文件名 无限制 输出所有的文件夹名和文件名 import os# 输出所有的文件夹名和文件名 pa ...
- 使用NPOI按照word模板文件生成新的word文件
/// <summary>/// 按照word模板文件 生成新word文件/// </summary>/// <param name="tempFile&quo ...
最新文章
- 【带你重拾Redis】Redis事务
- 使用wxSqlite3来解决sqlite加密问题zz
- 硬盘安装Windows 7和Ubuntu 10.04双系统
- java字符后移_java把字符串参数往后移3位后输出
- 克鲁斯卡尔重构树小结
- XidianOJ 1175: count
- Oracle 怎么开启,关闭归档
- leetcode—13.链表基本操作类题目python解答
- BZOJ_P3110 [ZJOI2013]K大数查询(线段树+整体二分)
- 电商打折套路分析 —— Python数据分析练习
- KODI | 智能电视系统
- tomcat 乱码问题
- 爬取每日必应图片,python爬虫简单入门
- 鸿蒙手机什么时候可以上线?在你有钱的时候!
- 烤仔的朋友们丨详解数字美元白皮书:双层架构、通证化、汇款通道
- 计算机网络——Physical_Layer
- 跨平台App开发的新趋势
- 如何系统学习VCU电控开发
- MATLAB中图片字符分割,matlab字符分割方法
- 搭建在线帮助中心,轻松帮助客户解决问题
热门文章
- [论文笔记]Vision-based Control of 3D Facial Animation
- ubuntu 18改MAC桌面
- Android 实现扫描二维码功能
- oppo手机工程模式清除数据需要密码_普通人也可以做码农?黑客教你如何在手机上开发运用代码...
- 小熊派鸿蒙开发板,小熊派-鸿蒙#183;季开发板入门(一)
- FL Studio混合器之效果器插槽部分讲解
- 红耳朵象全国战略,让大众享受上门洗车的福利
- Redis高级特性RDB、AOF、事务、Stream、Pipeline和Lua脚本
- 计算机网络怎么换ip,怎么更改电脑上网的IP地址
- 二次元壁纸 | 心情烦躁?换上喜欢的手机壁纸