这几天刚刚遇到一个问题:java操作word文档。
研究了下下:首先需要下载jar包支持,我个人使用的是jacob1.9.jar 。
仔细观察发现java操作word 格式很固定的。
我要实现的功能是根据模板复制出一份word 并把其中的标记文字替换成之后要改的文字。 功能基本实现
1新建java项目 导入jar包
2workMarker.java
package jacob;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordMaker {
Map<String, String> info;
private String textPath;
private static String outWord;
protected ActiveXComponent word;
protected Dispatch documents;
protected Dispatch document;
private Dispatch selection;
protected Dispatch range;
protected Dispatch find;
protected Dispatch paragraphs;
protected Dispatch tables;
public static final int wdFindContinue = 1;
public WordMaker() {
super();
}
/**
* 根据条件创建word
* @param textPath 模板文档路径
* @param outWord 新生成文档路径
* @param info 替换文本Map<String,String> key要替换的文本 value替换后的文本
*/
public void buildWord(String textPath, String outWord, Map<String, String> info) {
if (textPath != null && new File(textPath).exists()) {
this.info = info;
this.textPath = textPath;
this.outWord = outWord;
initFields();
}
}
/**
* 初始化jacob组件的相关Dispatch对象参数
*
*/
protected void initFields() {
try {
this.word = new ActiveXComponent("Word.Application"); //
this.word.setProperty("Visible", new Variant(false));
this.documents = this.word.getProperty("Documents").toDispatch();
this.document = Dispatch.call(this.documents, "Open", textPath)
.toDispatch();
this.selection = this.word.getProperty("Selection").toDispatch();
this.find = Dispatch.call(this.selection, "Find").toDispatch();
this.paragraphs = Dispatch.get(document, "Paragraphs").toDispatch();
this.tables = Dispatch.get(document, "Tables").toDispatch();
this.range = Dispatch.get(selection, "Range").toDispatch();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getCause().toString());
ex.printStackTrace();
}
saveAsOutputFile();
closeTemplate();
insertWord();
closeOutWord();
quit();
ComThread.Release();
}
/**
* 以流的形式保存输出
*
* @return 返回生成的doc文档的输出流
*
*/
protected void quit() {
if (this.word != null) {
this.word.invoke("Quit", new Variant[] {});
this.word = null;
}
}
protected void saveAsOutputFile() {
if (this.document != null) {
Dispatch.invoke(this.document, "SaveAs", Dispatch.Method,
new Object[] { this.outWord, new Variant(0) }, new int[1]);
}
}
protected void closeTemplate() {
if (this.textPath != null && this.document != null) {
Dispatch.call(this.document, "Close", new Variant(false));
this.document = null;
}
}
protected void closeOutWord() {
if (this.outWord != null && this.document != null) {
Dispatch.call(this.document, "Close", new Variant(false));
this.document = null;
}
}
public boolean insertWord() {
if (info != null && info.size() > 0) {
for (Iterator it = info.keySet().iterator(); it.hasNext();) {
String lkey = it.next().toString(); // 名
String lvalue = (String) info.get(lkey);// 值
replaceWord(lkey, lvalue);
}
}
return false;
}
/**
* 用于给指定的word文档中某处字符串做替换
*
* @param textPath
* 待替换的word文档
* @param targetWord
* 待替换的字符串
* @param replaceWord
* 要替换成的字符串
*/
public static void replaceWord(String targetWord, String replaceWord) {
ActiveXComponent app = new ActiveXComponent("Word.Application");// 启动word
try {
app.setProperty("Visible", new Variant(false));// 设置word不可见
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.invoke(
docs,
"Open",
Dispatch.Method,
new Object[] { outWord, new Variant(false),
new Variant(false) }, new int[1]).toDispatch();
// 打开word文件,注意这里第三个参数要设为false,这个参数表示是否以只读方式打开,
// 因为我们要保存原文件,所以以可写方式打开。
Dispatch selection = app.getProperty("Selection").toDispatch();// 获得对Selection组件
Dispatch.call(selection, "HomeKey", new Variant(6));// 移到开头
Dispatch find = Dispatch.call(selection, "Find").toDispatch();// 获得Find组件
Dispatch.put(find, "Text", targetWord);// 查找字符串targetWord
Dispatch.call(find, "Execute");// 执行查询
Dispatch.put(selection, "Text", replaceWord);// 替换为replaceWord
Dispatch.call(doc, "Save");// 保存
Dispatch.call(doc, "Close", new Variant(false));
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
/**
* 创建一个word文档
*
* @param txtContent
* 要写入word文档的内容
* @param fileName
* 要保存的word文档路径
*/
public static void createWordFile(String txtContent, String fileName) {
ActiveXComponent app = new ActiveXComponent("Word.Application");// 启动word
try {
app.setProperty("Visible", new Variant(false));// 设置word不可见
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(docs, "Add").toDispatch();
Dispatch selection = Dispatch.get(app, "Selection").toDispatch();
Dispatch.put(selection, "Text", txtContent);
Dispatch.call((Dispatch) Dispatch.call(app, "WordBasic")
.getDispatch(), "FileSaveAs", fileName);
Variant f = new Variant(false);
Dispatch.call(doc, "Close", f);
} catch (Exception e) {
e.printStackTrace();
} finally {
app.invoke("Quit", new Variant[] {});
app.safeRelease();
}
}
/**
* 根据现有的txt文本来创建word
*
* @param txt
* txt文本路径
* @param wordFile
* word路径
*/
public static void createWordWithTxt(String txt, String wordFile) {
String txtContent = null;
try {
txtContent = bufferedReader(txt);
} catch (IOException e) {
e.printStackTrace();
}
createWordFile(txtContent, wordFile);
}
/**
* 读文件
*
* @param path
* @return
* @throws IOException
*/
public static String bufferedReader(String path) throws IOException {
File file = new File(path);
if (!file.exists() || file.isDirectory())
throw new FileNotFoundException();
BufferedReader br = new BufferedReader(new FileReader(file));
String temp = null;
StringBuffer sb = new StringBuffer();
temp = br.readLine();
while (temp != null) {
sb.append(temp + " ");
temp = br.readLine();
}
return sb.toString();
}
/**
* 给指定的word文档在字符串指定位置插入图片
*
* @param wordFile
* word文档
* @param imagePath
* 待添加图片的路径
* @param str
* 指定的字符串位置
*/
public static void insertImage(String wordFile, String imagePath,
String tarStr) {
ActiveXComponent app = new ActiveXComponent("Word.Application");// 启动word
try {
app.setProperty("Visible", new Variant(false));// 设置word不可见
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.invoke(
docs,
"Open",
Dispatch.Method,
new Object[] { wordFile, new Variant(false),
new Variant(false) }, new int[1]).toDispatch();
// 打开word文件,注意这里第三个参数要设为false,这个参数表示是否以只读方式打开,
// 因为我们要保存原文件,所以以可写方式打开。
Dispatch selection = app.getProperty("Selection").toDispatch();
Dispatch.call(selection, "HomeKey", new Variant(6));// 移到开头
Dispatch find = Dispatch.call(selection, "Find").toDispatch();// 获得Find组件
Dispatch.put(find, "Text", tarStr);// 查找字符串tarStr
Dispatch.call(find, "Execute");// 执行查询
Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
"AddPicture", imagePath);// 在指定位置插入图片
Dispatch.call(doc, "Save");// 保存
Dispatch.call(doc, "Close", new Variant(false));
} catch (Exception e) {
e.printStackTrace();
} finally {
app.invoke("Quit", new Variant[] {});
app.safeRelease();
}
}
/**
* 在指定word文档的指定位置创建一个表格
*
* @param wordFile指定word文档
* @param pos
* 指定位置
*
* @param numCols
* 列数
* @param numRows
* 行数
*/
public static void createTable(String wordFile, String pos, int numCols,
int numRows) {
ActiveXComponent app = new ActiveXComponent("Word.Application");// 启动word
Dispatch selection = null;
Dispatch doc = null;
Dispatch docs = null;
boolean b = false;
try {
app.setProperty("Visible", new Variant(false));// 设置word不可见
docs = app.getProperty("Documents").toDispatch();
doc = Dispatch.invoke(
docs,
"Open",
Dispatch.Method,
new Object[] { wordFile, new Variant(false),
new Variant(false) }, new int[1]).toDispatch();
// 打开word文件,注意这里第三个参数要设为false,这个参数表示是否以只读方式打开,
// 因为我们要保存原文件,所以以可写方式打开。
selection = app.getProperty("Selection").toDispatch();
} catch (Exception e) {
e.printStackTrace();
}
if (pos == null || pos.equals(""))
b = false;
// 从selection所在位置开始查询
Dispatch find = app.call(selection, "Find").toDispatch();
// 设置要查找的内容
Dispatch.put(find, "Text", pos);
// 向前查找
Dispatch.put(find, "Forward", "True");
// 设置格式
Dispatch.put(find, "Format", "True");
// 大小写匹配
Dispatch.put(find, "MatchCase", "True");
// 全字匹配
Dispatch.put(find, "MatchWholeWord", "True");
// 查找并选中
b = Dispatch.call(find, "Execute").getBoolean();
// 创建表格
if (b) {
Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
Dispatch newTable = Dispatch.call(tables, "Add", range,
new Variant(numRows), new Variant(numCols)).toDispatch();
Dispatch.call(selection, "MoveRight");
} else
System.out.println("没有找到指定的位置,请检查是否存在这样的位置。");
try {
Dispatch.call(doc, "Save");// 保存
Dispatch.call(doc, "Close", new Variant(false));
} catch (Exception e) {
e.printStackTrace();
} finally {
app.invoke("Quit", new Variant[] {});
app.safeRelease();
}
}
}
3,测试 Test.java
package com.cgrj.jacob;
import java.util.HashMap;
import java.util.Map;
import com.jacob.com.ComThread;
public class Text {
public static void main(String[] args) {
Map<String, String> info = new HashMap<String, String>();
info.put("xwdd", "1234");
info.put("xwr", "safdg");
WordMaker f = new WordMaker();
f.buildWord("f:\\d.doc", "f:\\aa.doc", info);
}
}
用Map保存需要替换的文字
例如word模板里有xwdd 就会被替换成“我”
但是目前有两个小问题亟待解决:
1,操作时 文档必须关闭 要不就会报错。
2,如果是web项目 ,客户端操作的话 实际上是在服务器上生成和操作的 ,这不是我们想要的效果。
后来发现js也是可以操作word的 他是在客户端进行操作。
var word;
word = new ActiveXObject("Word.Application");
var range = word.Range;
word.Visible = true;
var path = "filepath";
word.Documents.Open(path);
range = word.ActiveDocument.Bookmarks("bookmark").Range;
range.InsertBefore("哈哈哈哈哈哈"); //书签后插入内容
//-----以下代码段附加保护及取消保护文档功能----
//保护文档,书签处可编辑
range.select();//选定书签内容
var psw='123'
word.ActiveDocument.BookMarks("bookmark").Range.Editors.Add(-1); //常量:wdEditorEveryone=-1
word.ActiveDocument.Protect(3,false,psw,false,false);//常量:wdAllowOnlyReading=3
//取消保护文档
word.ActiveDocument.Unprotect(psw);
//-----------------------end--------------
http://516263736.blog.163.com/blog/static/7141143520107111425939/
个人觉得做web项目的话用java操作会更好一点。可以通过上传和下载来实现客户端的操作。毕竟客户端不一定安装了word
我遗留的问希望高手看了也帮帮忙