近期项目需要根据word模板动态生成word文档,在网上看了些资料,在介绍的几种方法中选择了jacob方式,根据网上的资料,能解决大部分的问题,比如,生成表格,设置字体、段落格式,插入图片、设置图片格式。
可是项目中生成的word 文档还需要生成目录页,分割章节,网上找了很多资料,都没找到相关的方法,最后看到一篇博客,提供了一个思路,Java通过jacob操作office的宏,加上之前有过写宏的经验,一步步的实验终于搞定了。
博客地址:http://men4661273.iteye.com/blog/2097871
package com.jacob.newdemo;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordBean {
// word文档
private Dispatch doc;
// word运行程序对象
private ActiveXComponent word;
// 所有word文档集合
private Dispatch documents;
// 选定的范围或插入点
private Dispatch selection;
private boolean saveOnExit = true;
/**
* @param visible
* true表示word应用程序可见
*/
public WordBean(boolean visible) {
// TODO Auto-generated constructor stub
if (word == null) {
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(visible));
}
if (documents == null)
documents = word.getProperty("Documents").toDispatch();
}
/**
* 创建一个新的word文档
*/
public void createNewDocument() {
doc = Dispatch.call(documents, "Add").toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
/**
* 打开一个已存在的文档
*
* @param docPath
*/
public void openDocument(String docPath) {
closeDocument();
doc = Dispatch.call(documents, "Open", docPath).toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
/**
* 把选定的内容或插入点向上移动
*
* @param pos
* 移动的距离
*/
public void moveUp(int pos) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < pos; i++)
Dispatch.call(selection, "MoveUp");
}
/**
* 把选定的内容或者插入点向下移动
*
* @param pos
* 移动的距离
*/
public void moveDown(int pos) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < pos; i++)
Dispatch.call(selection, "MoveDown");
}
/**
* 把选定的内容或者插入点向左移动
*
* @param pos
* 移动的距离
*/
public void moveLeft(int pos) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveLeft");
}
}
/**
* 把选定的内容或者插入点向右移动
*
* @param pos
* 移动的距离
*/
public void moveRight(int pos) {
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
for (int i = 0; i < pos; i++