3. 取得word文档的内容后,可以对其内容进行操作
Dispatch.call(wordContent, "InsertAfter", "这里是一个段落的内容");//插入一个段落
4. 设置刚插入的段落的文字格式
Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs").toDispatch(); // 所有段落
int paragraphCount = Dispatch.get(paragraphs, "Count").toInt(); // 一共的段落数
// 找到刚输入的段落,设置格式
Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",
new Variant(paragraphCount)).
toDispatch(); // 最后一段
Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range").
toDispatch();
Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch();
Dispatch.put(font, "Bold", new Variant(true)); // 设置为黑体
Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体
Dispatch.put(font, "Name", new Variant("宋体")); //
Dispatch.put(font, "Size", new Variant(12)); //小四
注意:如果想插入一个新的空白行,也需要设置段落的文字格式,否则新插入行的文字格式会于刚插入的段落的格式相同。
5. 将当前文档保存
Dispatch.call(document, "SaveAs", new Variant("C:
abc.doc")); // 保存一个新文档
6. 释放COM线程
ComThread.Release();//释放com线程。根据jacob的帮助文档,com的线程回收不由java的垃圾回收器处理
完整测试代码:(StudyJacob.java 附件中有本文章和java源文件)
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.jacob.com.ComThread;
public class StudyJacob {
public static void main(String[] args) {
ComThread.InitSTA();// 初始化com的线程,非常重要!!使用结束后要调用 realease方法
//Instantiate objWord //Declare word object
ActiveXComponent objWord = new ActiveXComponent("Word.Application");
//Assign a local word object
Dispatch wordObject = (Dispatch) objWord.getObject();
//Create a Dispatch Parameter to show the document that is opened
Dispatch.put((Dispatch) wordObject, "Visible", new Variant(true));// new Variant(true)表示word应用程序可见
//Instantiate the Documents Property
Dispatch documents = objWord.getProperty("Documents").toDispatch(); //documents表示word的所有文档窗口,(word是多文档应用程序)
//Add a new word document, Current Active Document
Dispatch document = Dispatch.call(documents, "Add").toDispatch(); // 使用Add命令创建一个新文档,用Open命令可以打开一个现有文档
Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容
Dispatch.call(wordContent, "InsertAfter", "这里是一个段落的内容");//插入一个段落
Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs").toDispatch(); // 所有段落
int paragraphCount = Dispatch.get(paragraphs, "Count").toInt(); // 一共的段落数
// 找到刚输入的段落,设置格式
Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",
new Variant(paragraphCount)).
toDispatch(); // 最后一段
Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range").
toDispatch();
Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch();
Dispatch.put(font, "Bold", new Variant(true)); // 设置为黑体
Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体
Dispatch.put(font, "Name", new Variant("宋体")); //
Dispatch.put(font, "Size", new Variant(12)); //小四
Dispatch.call(document, "SaveAs", new Variant("C:
abc.doc")); // 保存一个新文档
ComThread.Release();//释放com线程。根据jacob的帮助文档,com的线程回收不由java的垃圾回收器处理
}
}