java操作word_java操作word文档 √

1、一个jacob操作Word的例子,其他操作excel,pdf的sample里都有,可以作为java资料进行保留

import java.io.File;

import com.jacob.com.*;

import com.jacob.activeX.*;

public class WordTest {

public static void main(String[] args) {

WordBean word=new WordBean();

word.openWord(true);

word.createNewDocument();

word.insertText("Hello word.");

}

}

import com.jacob.activeX.*;

import com.jacob.com.*;

public class WordBean extends java.awt.Panel

{

private ActiveXComponent MsWordApp = null;

private Dispatch document = null;

public WordBean()

{

super();

}

public void openWord(boolean makeVisible)

{

//Open Word if we've not done it already

if (MsWordApp == null)

{

MsWordApp = new ActiveXComponent("Word.Application");

}

//Set the visible property as required.

Dispatch.put(MsWordApp, "Visible",

new Variant(makeVisible));

}

public void createNewDocument()

{

//Find the Documents collection object maintained by Word

Dispatch documents =

Dispatch.get(MsWordApp,"Documents").toDispatch();

//Call the Add method of the Documents collection to create

//a new document to edit

document = Dispatch.call(documents,"Add").toDispatch();

}

public void insertText(String textToInsert)

{

// Get the current selection within Word at the moment. If

// a new document has just been created then this will be at

// the top of the new doc

Dispatch selection =

Dispatch.get(MsWordApp,"Selection").toDispatch();

//Put the specified text at the insertion point

Dispatch.put(selection,"Text",textToInsert);

}

public void saveFileAs(String filename)

{

Dispatch.call(document,"SaveAs",filename);

}

public void printFile()

{

//Just print the current document to the default printer

Dispatch.call(document,"PrintOut");

}

public void closeDocument()

{

// Close the document without saving changes

// 0 = wdDoNotSaveChanges

// -1 = wdSaveChanges

// -2 = wdPromptToSaveChanges

Dispatch.call(document, "Close", new Variant(0));

document = null;

}

public void closeWord()

{

Dispatch.call(MsWordApp,"Quit");

MsWordApp = null;

document = null;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值