Java operation Word document encapsulation class

Source: Internet
Author: User

 

Based on Open-Source Project Jacob, it encapsulates common methods and interfaces for operating word. The Jacob Project is a tool for operating the COM interface through Java. This part of Code encapsulates the common COM interface for operating the word. Use it with Jacob. dll and Jacob. jar.

 

Import java. Io. file;
 
Import com. Jacob. ActiveX. activexcomponent;
Import com.jacb.com. comfailexception;
Import com.jacb.com. Dispatch;
Import com.jacb.com. Variant;
 
Final class wordbean {
/**
* Maximum number of Retries for reading COM interface exceptions.
*/
Private Static final int max_retry = 10;
/**
* Word documents.
*/
Private dispatch Doc;
/**
* Word running program object.
*/
Private activexcomponent wordapp = NULL;
/**
* Selected range or insertion point.
*/
Private dispatch selection;
/**
* Whether to save the document when exiting.
*/
Private Boolean saveonexit = true;
 
/**
* Constructor.
* @ Param show is visible.
*/
Public wordbean (final Boolean show ){
If (wordapp = NULL ){
Wordapp = new activexcomponent ("word. application ");
Wordapp. setproperty ("visible", new variant (show ));
}
}
 
/**
* Set the exit parameters.
* @ Param B Boolean true-save the file upon exit, false-do not save the file upon exit
*/
Public void setsaveonexit (
Final Boolean B ){
This. saveonexit = B;
}
 
/**
* Move the selected content or insertion point up.
* @ Param pos: movement distance
*/
Public void moveup (
Final int POS ){
 
If (selection = NULL ){
Selection = Dispatch. Get (wordapp, "selection"). todispatch ();
}
 
For (INT I = 0; I <Pos; I ++ ){
Dispatch. Call (selection, "moveup ");
}
}
 
/**
* Move the selected content or insertion point down.
* @ Param pos: movement distance
*/
Public void movedown (
Final int POS ){
 
If (selection = NULL ){
Selection = Dispatch. Get (wordapp, "selection"). todispatch ();
}
 
For (INT I = 0; I <Pos; I ++ ){
Dispatch. Call (selection, "movedown ");
}
}
 
/**
* Move the selected content or insertion point to the left.
* @ Param pos: movement distance
*/
Public void moveleft (
Final int POS ){
 
If (selection = NULL ){
Selection = Dispatch. Get (wordapp, "selection"). todispatch ();
}
 
For (INT I = 0; I <Pos; I ++ ){
Dispatch. Call (selection, "moveleft ");
}
}
 
/**
* Move the selected content or insertion point to the right.
* @ Param pos: movement distance
*/
Public void moveright (
Final int POS ){
 
If (selection = NULL ){
Selection = Dispatch. Get (wordapp, "selection"). todispatch ();
}
 
For (INT I = 0; I <Pos; I ++ ){
Dispatch. Call (selection, "moveright ");
}
}
 
/**
* Move the insert point to the first position of the file.
*/
Public void movestart (){
If (selection = NULL ){
Selection = Dispatch. Get (wordapp, "selection"). todispatch ();
}
 
Dispatch. Call (selection, "homekey", new variant (6 ));
}
 
/**
* Move the insert point to the end of the file.
*/
Public void moveend (){
If (selection = NULL ){
Selection = Dispatch. Get (wordapp, "selection"). todispatch ();
}
 
Dispatch. Call (selection, "endkey", new variant (6 ));
}
 
/**
* Increase indentation.
* @ Param POS indentation
*/
Public void listindent (
Final int POS ){
 
Dispatch range = Dispatch. Get (this. Selection, "range"). todispatch ();
Dispatch listformat = Dispatch. Get (range, "listformat"). todispatch ();
For (INT I = 0; I <Pos; I ++ ){
Dispatch. Call (listformat, "listindent ");
}
}
 
/**
* Reduce indentation.
* @ Param POS indentation
*/
Public void listoutdent (
Final int POS ){
 
Dispatch range = Dispatch. Get (this. Selection, "range"). todispatch ();
Dispatch listformat = Dispatch. Get (range, "listformat"). todispatch ();
For (INT I = 0; I <Pos; I ++ ){
Dispatch. Call (listformat, "listoutdent ");
}
}
 
/**
* Press enter to wrap the line.
*/
Public void enter (){
Int Index = 1;
While (true ){
Try {
Dispatch. Call (this. Selection, "typeparagraph ");
Break;
} Catch (comfailexception e ){
If (index ++> = max_retry ){
Throw E;
} Else {
Continue;
}
}
}
}
 
/**
* Insert a form feed.
*/
Public void insertpagebreak (){
Dispatch. Call (this. Selection, "insertbreak", new variant (2 ));
}
 
/**
* Set whether the word document is visible.
* @ Param isvisvisible
*/
Public void setisvisible (
Final Boolean isvisible ){
 
Wordapp. setproperty ("visible", new variant (isvisible ));
}
 
/**
* Determine whether a document exists.
* @ Param docname document name.
* @ Return Boolean whether it exists.
*/
Private Boolean isexist (
Final string docname ){
 
Boolean result = false;
File file = new file (docname );
Result = file. exists ();
File = NULL;
Return result;
}
 
/**
* Get the file name.
* @ Param docname file path.
* @ Return file name
*/
Public String getfilename (
Final string docname ){
 
Int Pos = docname. lastindexof ("\\");
Return docname. substring (Pos + 1 );
}
 
/**
* Open the document.
* @ Param docname file path.
* @ Throws wordexception exception
*/
Public void opendocument (
Final string docname)
Throws wordexception {
 
Dispatch docs = wordapp. getproperty ("events"). todispatch ();
 
If (isexist (docname )){
This. closedocument ();
Doc = Dispatch. Call (Docs, "open", docname). todispatch ();
} Else {
Wordapp. Invoke ("quit", new variant [] {});
New wordexception ("[Open Doc failed]: file ["
+ Docname + "] isn' t existed! ");
}
 
Selection = Dispatch. Get (wordapp, "selection"). todispatch ();
}
 
/**
* Add a new document.
* @ Param docname file path.
* @ Throws wordexception exception
*/
Public void newdocument (
Final string docname)
Throws wordexception {
 
Try {
Dispatch docs = wordapp. getproperty ("events"). todispatch ();
Doc = Dispatch. Call (Docs, "add"). todispatch ();
Selection = Dispatch. Get (wordapp, "selection"). todispatch ();
} Catch (com.jacb.com. comfailexception CFE ){
Throw new wordexception (CFE. getmessage ());
} Catch (com.jacb.com. comexception CE ){
Throw new wordexception (Ce. getmessage ());
}
}
 
/**
* Insert a text clip.
* @ Param texttoinsert text
* @ Param Style
*/
Public void inserttext (
Final string texttoinsert,
Final string style ){
 
Dispatch. Put (selection, "text", texttoinsert );
Dispatch. Put (selection, "style", getoutlinestyle (style ));
Dispatch. Call (selection, "moveright ");
}
 
/**
* Insert an image.
* @ Param ImagePath: Specifies the image path.
* @ Param style: Image Style
*/
Public void insertimage (
Final string ImagePath,
Final string style ){
 
Dispatch. Call (dispatch. Get (selection, "inlineshapes ")
. Todispatch (), "addpicture", ImagePath );
 
Dispatch. Call (selection, "moveright ");
Dispatch. Put (selection, "style", getoutlinestyle (style ));
This. Enter ();
}
 
/**
* Get the style object of the corresponding name.
* @ Param style name.
* @ Return style object
*/
Public variant getoutlinestyle (
Final string style ){
 
Int Index = 1;
While (true ){
Try {
Return dispatch. Call (
Dispatch.get(this.doc, "styles"). todispatch (),
"Item", new variant (style ));
} Catch (comfailexception e ){
If (index ++> = max_retry ){
Throw E;
} Else {
Continue;
}
}
}
}
 
/**
* Insert the title.
* @ Param text title text.
* @ Param style: sets the title type.
*/
Public void insertoutline (
Final string text,
Final string style ){
 
This. inserttext (text, style );
This. Enter ();
}
 
/**
* Insert directory.
* Tablesofcontents parameter description add (range as range, [useheadingstyles],
* [Upperheadinglevel], [lowerheadinglevel], [usefields], [tableid],
* -- Either of them can be [rightalignpagenumbers], [includepagenumbers], [addedstyles],
* -- This parameter must have a value, which must be a number. If it is other values, the message com.jacb.com. comfailexception is returned.
* [Usehyperlinks], [hidepagenumbersinweb], [useoutlinelevels])
*/
Public void inserttablesofcontents (){
Dispatch tablesofcontents = dispatch.get(this.doc, "tablesofcontents ")
. Todispatch ();
 
Dispatch range = Dispatch. Get (this. Selection, "range"). todispatch ();
// The maximum number of dispatch. Call parameters is 9. If more than 9 parameters are specified, use dispatch. calln or dispathc. invoke.
/*
* Dispatch. Invoke (tablesofcontents, "add", dispatch. method, new
* Object [] {range, new variant (true), new variant (1), new variant (3), new
* Variant (true), new
* Variant ("1"), new variant (true), new variant (true)}, new int [10]);
*/
Dispatch. calln (tablesofcontents, "add", new object [] {
Range,
New variant (true ),
New variant (1 ),
New variant (3 ),
New variant (false ),
New variant (true ),
New variant (true ),
New variant ("1 "),
New variant (true ),
New variant (true )});
}
 
/**
* Search for text from the selected content or insertion point.
* @ Param tofindtext the text to be searched
* @ Return Boolean true-find and select the text, false-No text found
*/
Public Boolean find (
Final string tofindtext ){
 
If (tofindtext = NULL
| Tofindtext. Equals ("")){
Return false;
}
 
// Query from the position of Selection
Dispatch find = Dispatch. Call (selection, "find"). todispatch ();
// Set the content to be searched
Dispatch. Put (find, "text", tofindtext );
// Forward search
Dispatch. Put (find, "forward", "true ");
// Set the format
Dispatch. Put (find, "format", "true ");
// Case-insensitive match
Dispatch. Put (find, "matchcase", "true ");
// Full match
Dispatch. Put (find, "matchwholeword", "true ");
// Search and select
Return dispatch. Call (find, "execute"). getboolean ();
}
 
/**
* Set the selected content to replace the text.
* @ Param tofindtext search string
* @ Param newtext content to be replaced
* @ Return Boolean true-find and select the text, false-No text found
*/
Public Boolean replacetext (
Final string tofindtext,
Final string newtext ){
 
If (! Find (tofindtext )){
Return false;
}
 
Dispatch. Put (selection, "text", newtext );
Return true;
}
 
/**
* Create a table.
* @ Param numcols: Number of Columns
* @ Param numrows: number of rows
* @ Param AutoFormat default format
* @ Return table object
*/
Public dispatch createtable (
Final int numrows,
Final int numcols,
Final int AutoFormat ){
 
Int Index = 1;
While (true ){
Try {
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 ");
Dispatch. Call (newtable, "AutoFormat", new variant (AutoFormat ));
Return newtable;
} Catch (comfailexception e ){
If (index ++> = max_retry ){
Throw E;
} Else {
Continue;
}
}
}
}
 
/**
* Fill in the data in the specified header.
* @ Param Table
* @ Param cellcodecomx column number
* @ Param TXT text
* @ Param Style
*/
Public void puttableheader (
Final dispatch table,
Final int cellcosponx,
Final string txt,
Final string style ){
 
Dispatch cell = Dispatch. Call (table, "cell", new variant (1 ),
New variant (cellcodecomx). todispatch ();
 
Dispatch. Call (cell, "select ");
Dispatch. Put (selection, "text", txt );
Dispatch. Put (this. Selection, "style", getoutlinestyle (style ));
}
 
/**
* Fill in the data in the specified cell.
* @ Param Table
* @ Param cellrowidx row number
* @ Param cellcodecomx column number
* @ Param TXT text
* @ Param Style
*/
Public void puttablecell (
Final dispatch table,
Final int cellrowidx,
Final int cellcosponx,
Final string txt,
Final string style ){
 
Dispatch cell = Dispatch. Call (table, "cell", new variant (cellrowidx ),
New variant (cellcodecomx). todispatch ();
 
Dispatch. Call (cell, "select ");
Dispatch. Put (selection, "text", txt );
Dispatch. Put (this. Selection, "style", getoutlinestyle (style ));
}
 
/**
* Close the current Word document.
*/
Private void closedocument (){
If (Doc! = NULL ){
Dispatch. Call (Doc, "save ");
Dispatch. Call (Doc, "close", new variant (saveonexit ));
Doc = NULL;
}
}
 
/**
* Save or save the file.
* @ Param savepath save or save it as a path
*/
Public void savefileas (
Final string savepath ){
 
Dispatch. Call (Doc, "saveas", savepath );
}
 
/**
* Close the document.
*/
Public void close (){
Closedocument ();
If (wordapp! = NULL ){
Dispatch. Call (wordapp, "quit ");
Wordapp = NULL;
}
Selection = NULL;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.