java,
java,
public class NewAWord<br>{<br> public NewAWord(){<br> // 初始化com的线程,非常重要!!使用结束后要调用 release方法 <br> ComThread.InitSTA();<br> // 初始化word应用程序,新建一个空白文档,取得文档内容对象<br> ActiveXComponent objWord = new ActiveXComponent("Word.Application"); <br> Dispatch wordObject = (Dispatch) objWord.getObject(); <br> Dispatch.put((Dispatch) wordObject, "Visible", new Variant(true));// new Variant(true)表示word应用程序可见 <br> //Tip:设置一个对象的属性的时候,利用Dispatch的put方法,给属性赋值。上面这行语句相当于vb的 wordObject.Visible = true 语句 <br> Dispatch documents = objWord.getProperty("Documents").toDispatch(); //documents表示word的所有文档窗口,(word是多文档应用程序) <br> Dispatch document = Dispatch.call(documents, "Add").toDispatch(); // 使用Add命令创建一个新文档,用Open命令可以打开一个现有文档 <br> //Tip:调用一个对象的方法的时候,利用Dispatch的call方法,上面的语句相当于vb的document = documents.Add() 语句。<br> Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容 <br> Dispatch.call(wordContent, "InsertAfter", "这里是一个段落的内容");//插入一个段落<br> //4. 设置刚插入的段落的文字格式 <br> Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs").toDispatch(); // 所有段落 <br> int paragraphCount = Dispatch.get(paragraphs, "Count").toInt(); // 一共的段落数 <br> // 找到刚输入的段落,设置格式 <br> Dispatch lastParagraph = Dispatch.call(paragraphs, "Item", <br> new Variant(paragraphCount)). toDispatch(); // 最后一段 <br> Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range"). toDispatch(); <br> Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch(); <br> Dispatch.put(font, "Bold", new Variant(true)); // 设置为黑体 <br> Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体 <br> Dispatch.put(font, "Name", new Variant("宋体")); // <br> Dispatch.put(font, "Size", new Variant(12)); //小四 <br> Dispatch.call(document, "SaveAs", new Variant("F:/abc.doc")); // 保存一个新文档<br> <span >//注意用ActiveXComponent调用word的quit方法</span><br> objWord.invoke("Quit", new Variant[] {});<br> ComThread.Release();//释放com线程。根据jacob的帮助文档,com的线程回收不由java的垃圾回收器处理 <br> }
?
1
public static void main(String[] args) {<br> new NewAWord(); <br> }
?
1
}
相关文章
- 暂无相关文章
用户点评