Java uses the Jsoup component to generate Word documents _java

Source: Internet
Author: User
Tags rowcount save file uuid stringbuffer

Take advantage of the Jsoup (Jsoup.parse (String html)) method that the HTML code will get. Then use Filewiter to write this HTML content to the local Template.doc file, if the article contains pictures, Template.doc will rely on your local image file path, if you change a name or change the path, and then open the Template.doc, The picture will not show up (a fork appears). To resolve this problem, use the Jsoup component to iterate through the contents of the HTML document, replace the IMG element with the identity of the ${image_, remove the SRC attribute from the IMG element, and then store it as a key-value pair, for example:

Copy Code code as follows:

map<integer,string> Imgmap = new hashmap<integer,string> ();
Imgmap.put (1, "D:\lucene.png");






At this point your HTML content becomes the following format: (for example)


Copy Code code as follows:

<body>

<p> Test Message 1</p>
<p>${image_1}<p>
<table>
<tr>
<td> <td>
</tr>
</table>
<p> Test Message 2</p>
<a href=http://www.jb51.net><p>${image_2}</p></a>
<p> Test Message 3</p>
</body>



After saving to the local file, use the Msofficegeneratorutils class (see below, based on open source component Jacob) to open the template.doc you saved, call Replacetext2image, Replace the picture ID of the above code with a picture, which eliminates the problem of the local picture path. Then call the Copy method, copy the entire document, close the Template.doc file, create a new doc file (createdocument), invoke the Paste method to paste the contents of the Template.doc you just copied, and save it. It's basically OK.


There is also an implicit problem with the contents of the entire Word document copy. When the content is too much to copy, when you close the Word program, talk about a dialog box asking if you want to apply the copied data to another program. The solution to this problem is simple, you can create a new document, enter a line of words, and then call the copy method before calling quit (quit the Word program method), and it will not prompt you when you close the Word program when you have less data copied. See the following code


Copy a *.doc document with less content to prevent the word program from being prompted with a large amount of copy content in memory, and whether it should be applied to another Program dialog box.


Copy Code code as follows:



Msofficeutils.createnewdocument ();


Msofficeutils.inserttext ("test message");


Msofficeutils.copy ();


Msofficeutils.close ();


Msofficeutils.quit ();


Jacob's link on the SourceForge


Jsoup official website


Msofficegeneratorutils


Package com.topstar.test;


Import Java.io.File;


Import java.io.IOException;


Import java.util.List;


Import com.jacob.activeX.ActiveXComponent;


Import Com.jacob.com.ComThread;


Import Com.jacob.com.Dispatch;


Import com.jacob.com.Variant;


/**


* Use Jacob to do the related work for Microsoft Office Word


*


* @author Xiaowu


* @category Topstar


* @version 1.0


* @since 2011-12-5


*/


public class Msofficegeneratorutils {


/**


* Microsoft Office Word Program objects


*/


Private activexcomponent word = null;


/**


* Word Active Document Object


*/


Private Dispatch document = NULL;


/**


* All Word Document objects


*/


Private Dispatch documents = NULL;


/**


* Selection represents the selection in the currently active document window. If nothing is selected in the document, this object represents the insertion point (that is, the position of the cursor). &lt;br/&gt;


* Only one Selection object can exist in each document window, and only one active Selection object can exist throughout the application


*/


Private Dispatch selection = null;


/**


* The Range object represents a contiguous area of the document. Each Range object is defined by a starting character position and ending character position. &lt;br/&gt;


* The Range object is independent of the selection. You can define and process a range without changing the selection. You can also define multiple scopes in your document. But there is only one selection in each document


*/


Private Dispatch range = null;


/**


* PageSetup object contains settings properties for all pages of the document (such as paper size, left margin, bottom margin)


*/


Private Dispatch pageSetup = null;


/**


* All table objects in the document


*/


Private Dispatch tables = null;


/** Single Table Object * *


Private Dispatch table = null;


/** all row objects in the table * *


Private Dispatch rows = null;


/** all Column objects in the table * *


Private Dispatch cols = null;


/** Table Specify Line Object


Private Dispatch row = null;


/** table Specify Column object


Private Dispatch col = null;


/** the specified cell in the table * *


Private Dispatch cell = null;


/** Font * *


Private Dispatch font = NULL;


/** Alignment Method * *


Private Dispatch alignment = NULL;


/**


* Construction Method


*


* @param visible


* Set whether the program is visible when you build a Word document


*/


Public Msofficegeneratorutils (Boolean visible) {


if (This.word = = null) {


Initializing Microsoft Office Word instances


This.word = new Activexcomponent ("Word.Application");


This.word.setProperty ("Visible", New Variant (Visible));


Disable macros


This.word.setProperty ("AutomationSecurity", New Variant (3));


}


if (this.documents = null)


This.documents = Word.getproperty ("Documents"). Todispatch ();


}


/**


* Set page orientation and margins


*


* @param orientation


* Page orientation


* &lt;ul&gt;


* &lt;li&gt;0 Transverse &lt;/li&gt;


* &lt;li&gt;1 longitudinal &lt;/li&gt;


* &lt;/ul&gt;


* @param leftMargin


* Left margin


* @param rightMargin


* Right Margin


* @param topMargin


* Top Margin


* @param buttommargin


* Bottom Margin


*/


public void Setpagesetup (int orientation, int leftMargin, int rightMargin,


int topMargin, int buttommargin) {


if (This.pagesetup = null)


This.getpagesetup ();


Dispatch.put (PageSetup, "orientation", orientation);


Dispatch.put (PageSetup, "LeftMargin", LeftMargin);


Dispatch.put (PageSetup, "RightMargin", RightMargin);


Dispatch.put (PageSetup, "TopMargin", TopMargin);


Dispatch.put (PageSetup, "BottomMargin", Buttommargin);


}


/**


* Open Word Document


*


* @param Docpath


* Word Document Path


* @return Open Document Object


*/


Public Dispatch OpenDocument (String docpath) {


This.document = Dispatch.call (documents, "Open", Docpath). Todispatch ();


This.getselection ();


This.getrange ();


This.getalignment ();


This.getfont ();


This.getpagesetup ();


return this.document;


}


/**


* Create a new document


*


* @return Document Object


*/


Public Dispatch CreateNewDocument () {


This.document = Dispatch.call (documents, "ADD"). Todispatch ();


This.getselection ();


This.getrange ();


This.getpagesetup ();


This.getalignment ();


This.getfont ();


return this.document;


}


/**


* Get the selected content or insertion point


*


* @return Selection


*/


Public Dispatch getselection () {


This.selection = Word.getproperty ("Selection"). Todispatch ();


return this.selection;


}


/**


* Gets the part of the current document that can be modified, provided that the selection is required


*


* @return Range


*/


Public Dispatch GetRange () {


This.range = Dispatch.get (this.selection, Range). Todispatch ();


return this.range;


}


/**


* Get the page properties of the current document


*/


Public Dispatch Getpagesetup () {


if (this.document = null)


return this.pagesetup;


This.pagesetup = Dispatch.get (this.document, "PageSetup"). Todispatch ();


return this.pagesetup;


}


/**


* Move the selection or insertion point up


*


* @param count


* Move the distance


*/


public void moveUp (int count) {


for (int i = 0; i &lt; count; i++)


Dispatch.call (this.selection, "MoveUp");


}


/**


* Move the selection or insertion point down


*


* @param count


* Move the distance


*/


public void MoveDown (int count) {


for (int i = 0; i &lt; count; i++)


Dispatch.call (this.selection, "MoveDown");


}


/**


* Move the selection or insertion point to the left


*


* @param count


* Move the distance


*/


public void MoveLeft (int count) {


for (int i = 0; i &lt; count; i++)


Dispatch.call (this.selection, "MoveLeft");


}


/**


* Move the selection or insertion point to the right


*


* @param count


* Move the distance


*/


public void MoveRight (int count) {


for (int i = 0; i &lt; count; i++)


Dispatch.call (this.selection, "moveright");


}


/**


* Perform a hard wrap (enter)


*


* @param count


* Line of Change


*/


public void Enterdown (int count) {


for (int i = 0; i &lt; count; i++)


Dispatch.call (this.selection, "typeparagraph");


}


/**


* Move the insertion point to the first position of the file


*/


public void MoveStart () {


Dispatch.call (this.selection, "HomeKey", New Variant (6));


}


/**


* Move the insertion point to the end of the file


*/


public void MoveEnd () {


Dispatch.call (Selection, "EndKey", New Variant (6));


}








/**


* Find text from selection or insertion point


*


* @param tofindtext


* What to look for


* @return The contents of the query and select


*/


public boolean find (String tofindtext) {


Start Query from selection location


Dispatch find = Dispatch.call (this.selection, "find"). Todispatch ();


Set the hot? br/&gt; Dispatch.put (Find, "Text", Tofindtext);


Look forward


Dispatch.put (Find, "Forward", "True");


Set format


Dispatch.put (Find, "Format", "True");


Case matching


Dispatch.put (Find, "matchcase", "True");


Whole Word match


Dispatch.put (Find, "MatchWholeWord", "True");


Find and select


Return Dispatch.call (Find, "Execute"). Getboolean ();


}


/**


* Replace the selected content


*


* @param NewText


* What to replace


*/


public void replace (String newtext) {


Set alternate text


Dispatch.put (this.selection, "Text", NewText);


}


/**


* Global Substitution


*


* @param oldtext


* What to replace


* @param replaceobj


* Replaced content


*/


public void ReplaceAll (String oldtext, Object replaceobj) {


Move the insertion point to the beginning of the file


MoveStart ();


Table Replacement method


String NewText = (string) replaceobj;


How to replace pictures


if (Oldtext.indexof ("image")!=-1 | | | newtext.lastindexof (". bmp")!=-1 | | newtext.lastindexof (". jpg")!=-1 | | newtext.la Stindexof (". gif")!=-1) {


while (find (OldText)) {


Insertimage (NewText);


Dispatch.call (this.selection, "moveright");


}


Text mode


} else {


while (find (OldText)) {


Replace (NewText);


Dispatch.call (this.selection, "moveright");


}


}


}





/**


* Replace the specified content with a picture


* @param content specified by ReplaceText


* @param imgpath Picture path


*/


public void Replacetext2image (String replacetext,string imgpath) {


MoveStart ();


while (find (ReplaceText)) {


Insertimage (Imgpath);


MoveEnd ();


Enterdown (1);


}


}


/**


* Replace the picture with the current insertion point


*


* @param ImagePath


* The path of the picture


*/


public void Insertimage (String imagepath) {


Dispatch.call (Dispatch.get (Selection, "InlineShapes"). Todispatch (), "AddPicture", ImagePath);


}


/**


* Merge Cells


*


* @param tableindex


* Form subscript, starting from 1


* @param fstcellrowidx


* Start line


* @param fstcellcolidx


* Start column


* @param seccellrowidx


* End Line


* @param seccellcolidx


* End Column


*/


public void Mergecell (int tableindex, int fstcellrowidx, int fstcellcolidx,


int seccellrowidx, int seccellcolidx) {


GetTable (Tableindex);


Dispatch Fstcell = dispatch.call (table, "Cell",


New Variant (FSTCELLROWIDX), new variant (FSTCELLCOLIDX)


. Todispatch ();


Dispatch Seccell = dispatch.call (table, "Cell",


New Variant (SECCELLROWIDX), new variant (SECCELLCOLIDX)


. Todispatch ();


Dispatch.call (Fstcell, "Merge", Seccell);


}


/**


* Split the current cell


*


* @param numrows


* Split number of lines, if you do not want to split the branch, please specify 1


* @param numcolumns


* Split number of columns, if you do not want to split the column, specify 1


*/


public void Splitcell (int numrows, int numcolumns) {


Dispatch.call (This.cell, "Split", new Variant (NumRows), new variant (


NumColumns));


}


/**


* Write content to the table


*


* @param list


* What to write &lt;br/&gt;


* Note: the list.size () should be consistent with table rows, and the length property of the string array should be consistent with the table's columns


*/


public void inserttotable (list&lt;string[]&gt; List) {


if (list = = NULL | | list.size () &lt;= 0)


Return


if (this.table = null)


Return


for (int i = 0; i &lt; list.size (); i++) {


string[] STRs = List.get (i);


for (int j = 0; J &lt; Strs.length; J + +) {


Iterate through each of the tables. Cell, how many times do you want to fill in the hot 菔? Ken joyriding br/&gt; Dispatch cell = This.getcell (i + 1, j + 1);


Select this cell


Dispatch.call (Cell, "select");


Write hot 莸 sauce say ピ? piecemeal br/&gt; dispatch.put (this.selection, "Text", strs[j));


Move the insertion point to the next one?? Position


}


This.movedown (1);


}


Line Wrap


This.enterdown (1);


}


/**


* Insert text content to the current insertion point


*


* @param list


* The content to insert, List.size () represents the number of rows


*/


public void Inserttodocument (list&lt;string&gt; List) {


if (list = = NULL | | list.size () &lt;= 0)


Return


if (this.document = null)


Return


for (String str:list) {


Dispatch.put (this.selection, "Text", str);


This.movedown (1);


This.enterdown (1);


}


}


/**


* Inserts text at the current insertion point


*


* @param inserttext


* Text to insert


*/


public void Inserttotext (String inserttext) {


Dispatch.put (this.selection, "Text", inserttext);


}


/**


* Inserts a string at the current insertion point, and when you insert a line of text by using this method, Word selects it by default, and if you call this method, it overwrites the original content, so after calling this method, remember to call moveright and move the offset one position to the right.


* @param newtext The new string to insert


*/


public void InsertText (String newtext) {


Dispatch.put (Selection, "Text", NewText);


}


/**


* Create a new table


*


* @param rowcount


* Line


* @param colcount


* Column


* @param width


* Table Border


* &lt;ul&gt;


* &lt;li&gt;0 No Border &lt;/li&gt;


* &lt;li&gt;1 has a border &lt;/li&gt;


* &lt;/ul&gt;


* @return Table objects


*/


Public Dispatch createnewtable (int rowcount, int colcount, int width) {


if (this.tables = null)


This.gettables ();


This.getrange ();


if (RowCount &gt; 0 &amp;&amp; colcount &gt; 0)


this.table = Dispatch.call (This.tables, "Add", This.range,


New Variant (ROWCOUNT), new variant (ColCount),


New Variant (width)). Todispatch ();


return this.table;


}


/**


* Get all the table objects in the current document object


*


* @return Tables


*/


Public Dispatch Gettables () {


if (this.document = null)


return this.tables;


This.tables = Dispatch.get (this.document, "Tables"). Todispatch ();


return this.tables;


}


/**


* Get the number of all tables in the current document


*


* @return Number of forms


*/


public int Gettablescount () {


if (this.tables = null)


This.gettables ();


return Dispatch.get (Tables, "Count"). GetInt ();


}


/**


* Get Table object from index


*


* @param tableindex


* Index


* @return Table


*/


Public Dispatch gettable (int tableindex) {


if (this.tables = null)


This.gettables ();


if (tableindex &gt;= 0)


this.table = Dispatch.call (This.tables, "Item", New Variant (Tableindex)). Todispatch ();


return this.table;


}


/**


* Fill in the data in the specified cell


*


* @param tableindex


* Table Index


* @param cellrowidx


* Row Index


* @param cellcolidx


* Column Index


* @param txt


* Text


*/


public void Puttxttocell (int tableindex, int cellrowidx, int cellcolidx, String txt) {


GetTable (Tableindex);


Getcell (Cellrowidx, CELLCOLIDX);


Dispatch.call (This.cell, "select");


Dispatch.put (this.selection, "Text", txt);


}


/**


* Copy paragraphs from another document at the end of the current document


*


* @param Anotherdocpath


* Disk path to another document


* @param tableindex


* The ordinal number of the copied paragraph in the other document (starting from 1)


*/


public void Copyparagraphfromanotherdoc (String anotherdocpath, int paragraphindex) {


Dispatch wordcontent = Dispatch.get (this.document, "Content"). Todispatch (); Get the contents of the current document


Dispatch.call (wordcontent, "InsertAfter", "$selection $");//insert special character position insertion point


Copyparagraphfromanotherdoc (Anotherdocpath, Paragraphindex, "$selection $");


}


/**


* Copy the paragraph from another document at the location specified in the current document


*


* @param Anotherdocpath


* Disk path to another document


* @param tableindex


* The ordinal number of the copied paragraph in the other document (starting from 1)


* @param POS


* The location specified in the current document


*/


public void Copyparagraphfromanotherdoc (string anotherdocpath, int paragraphindex, string pos) {


Dispatch doc2 = null;


try {


DOC2 = Dispatch.call (documents, "Open", Anotherdocpath). Todispatch ();


Dispatch paragraphs = dispatch.get (doc2, "paragraphs"). Todispatch ();


Dispatch paragraph = dispatch.call (paragraphs, "Item", New Variant (Paragraphindex)). Todispatch ();


Dispatch range = Dispatch.get (paragraph, Range). Todispatch ();


Dispatch.call (range, "Copy");


if (This.find (POS)) {


GetRange ();


Dispatch.call (This.range, "Paste");


}


catch (Exception e) {


E.printstacktrace ();


finally {


if (doc2!= null) {


Dispatch.call (DOC2, "Close", New Variant (true));


DOC2 = null;


}


}


}


/**


* Copy a table from another document at the location specified in the current document


*


* @param Anotherdocpath


* Disk path to another document


* @param tableindex


* The ordinal number of the copied form in the other document (starting from 1)


* @param POS


* The location specified in the current document


*/


public void Copytablefromanotherdoc (String anotherdocpath, int tableindex,


String POS) {


Dispatch doc2 = null;


try {


DOC2 = Dispatch.call (documents, "Open", Anotherdocpath)


. Todispatch ();


Dispatch tables = Dispatch.get (doc2, "Tables"). Todispatch ();


Dispatch table = Dispatch.call (tables, "Item",


New Variant (Tableindex)). Todispatch ();


Dispatch range = dispatch.get (table, Range). Todispatch ();


Dispatch.call (range, "Copy");


if (This.find (POS)) {


GetRange ();


Dispatch.call (This.range, "Paste");


}


catch (Exception e) {


E.printstacktrace ();


finally {


if (doc2!= null) {


Dispatch.call (DOC2, "Close", New Variant (true));


DOC2 = null;


}


}


}


/**


* Copy pictures from another document at the location specified in the current document


*


* @param Anotherdocpath


* Disk path to another document


* @param shapeindex


* The position of the copied picture in another grid document


* @param POS


* The location specified in the current document


*/


public void Copyimagefromanotherdoc (String anotherdocpath, int shapeindex,


String POS) {


Dispatch doc2 = null;


try {


DOC2 = Dispatch.call (documents, "Open", Anotherdocpath)


. Todispatch ();


Dispatch shapes = dispatch.get (doc2, "InlineShapes"). Todispatch ();


Dispatch shape = dispatch.call (shapes, "Item",


New Variant (Shapeindex)). Todispatch ();


Dispatch Imagerange = Dispatch.get (Shape, Range). Todispatch ();


Dispatch.call (Imagerange, "Copy");


if (This.find (POS)) {


GetRange ();


Dispatch.call (This.range, "Paste");


}


catch (Exception e) {


E.printstacktrace ();


finally {


if (doc2!= null) {


Dispatch.call (DOC2, "Close", New Variant (true));


DOC2 = null;


}


}


}


/**


* Increase the row before the specified line in the specified table


*


* @param tableindex


* The nth table in the Word file (starting from 1)


* @param rowIndex


* Specify the ordinal of the line (starting from 1)


*/


public void Addtablerow (int tableindex, int rowIndex) {


GetTable (Tableindex);


Gettablerows ();


Gettablerow (RowIndex);


Dispatch.call (This.rows, "Add", New Variant (This.row));


}


/**


* Add a line before line 1th


*


* @param tableindex


* The nth table in the Word document (starting from 1)


*/


public void Addfirsttablerow (int tableindex) {


GetTable (Tableindex);


Gettablerows ();


Dispatch row = dispatch.get (rows, "a"). Todispatch ();


Dispatch.call (This.rows, "Add", New Variant (row));


}


/**


* Add one line before the last 1 lines


*


* @param tableindex


* The nth table in the Word document (starting from 1)


*/


public void Addlasttablerow (int tableindex) {


GetTable (Tableindex);


Gettablerows ();


Dispatch row = Dispatch.get (This.rows, "last"). Todispatch ();


Dispatch.call (This.rows, "Add", New Variant (row));


}


/**


* Add one line


*


* @param tableindex


* The nth table in the Word document (starting from 1)


*/


public void addrow (int tableindex) {


GetTable (Tableindex);


Gettablerows ();


Dispatch.call (This.rows, "Add");


}


/**


* Add a column


*


* @param tableindex


* The nth table in the Word document (starting from 1)


*/


public void Addcol (int tableindex) {


GetTable (Tableindex);


Gettablecolumns ();


Dispatch.call (This.cols, "Add"). Todispatch ();


Dispatch.call (This.cols, "AutoFit");


}


/**


* Add columns to the table before the specified column


*


* @param tableindex


* The nth table in the Word document (starting from 1)


* @param colindex


* Specify the ordinal of the column (starting from 1)


*/


public void Addtablecol (int tableindex, int colindex) {


GetTable (Tableindex);


Gettablecolumns ();


Gettablecolumn (Colindex);


Dispatch.call (This.cols, "Add", This.col). Todispatch ();


Dispatch.call (This.cols, "AutoFit");


}


/**


* Add a column before the 1th column


*


* @param tableindex


* The nth table in the Word document (starting from 1)


*/


public void Addfirsttablecol (int tableindex) {


GetTable (Tableindex);


Dispatch cols = Gettablecolumns ();


Dispatch col = dispatch.get (cols, "a"). Todispatch ();


Dispatch.call (cols, "Add", col). Todispatch ();


Dispatch.call (cols, "AutoFit");


}


/**


* Add a column before the last column


*


* @param tableindex


* The nth table in the Word document (starting from 1)


*/


public void Addlasttablecol (int tableindex) {


GetTable (Tableindex);


Dispatch cols = Gettablecolumns ();


Dispatch col = dispatch.get (cols, "last"). Todispatch ();


Dispatch.call (cols, "Add", col). Todispatch ();


Dispatch.call (cols, "AutoFit");


}


/**


* Get the number of columns in the current table


*


* Total @return Columns


*/


public int Gettablecolumnscount () {


if (this.table = null)


return 0;


Return Dispatch.get (This.cols, "Count"). GetInt ();


}


/**


* Get the number of rows in the current table


*


* Total @return Lines


*/


public int Gettablerowscount () {


if (this.table = null)


return 0;


Return Dispatch.get (this.rows, "Count"). GetInt ();


}


/**


* Get all Column objects in the current table


*


* @return cols


*/


Public Dispatch Gettablecolumns () {


if (this.table = null)


return this.cols;


This.cols = Dispatch.get (this.table, "Columns"). Todispatch ();


return this.cols;


}


/**


* Get all row objects of the current table


*


* @return Rows


*/


Public Dispatch gettablerows () {


if (this.table = null)


return this.rows;


This.rows = Dispatch.get (this.table, "Rows"). Todispatch ();


return this.rows;


}


/**


* Get the Column object of the current table based on the index


*


* @param columnindex


* Column Index


* @return Col


*/


Public Dispatch gettablecolumn (int columnindex) {


if (This.cols = null)


This.gettablecolumns ();


if (columnindex &gt;= 0)


This.col = Dispatch.call (This.cols, "Item",


New Variant (ColumnIndex)). Todispatch ();


return this.col;


}


/**


* Get the Row object of the current table based on the index


*


* @param rowIndex


* Row Index


* @return Row


*/


Public Dispatch gettablerow (int rowIndex) {


if (this.rows = null)


This.gettablerows ();


if (rowIndex &gt;= 0)


This.row = Dispatch.call (this.rows, "Item", New Variant (RowIndex))


. Todispatch ();


return this.row;


}


/**


* Automatically adjust all current forms


*/


public void autofittable () {


int count = This.gettablescount ();


for (int i = 0; i &lt; count; i++) {


Dispatch table = Dispatch.call (tables, "Item", new Variant (i + 1))


. Todispatch ();


Dispatch cols = dispatch.get (table, "Columns"). Todispatch ();


Dispatch.call (cols, "AutoFit");


}


}


/**


* Get cells in the current table based on row index and column index


*


* @param cellrowidx


* Row Index


* @param cellcolidx


* Column Index


* @return Cell Object


*/


Public Dispatch Getcell (int cellrowidx, int cellcolidx) {


if (this.table = null)


return This.cell;


if (cellrowidx &gt;= 0 &amp;&amp; cellcolidx &gt;= 0)


This.cell = Dispatch.call (this.table, "cell",


New Variant (CELLROWIDX), new variant (CELLCOLIDX)


. Todispatch ();


return This.cell;


}


public void Selectcell (int cellrowidx, int cellcolidx) {


if (this.table = null)


Return


Getcell (Cellrowidx, CELLCOLIDX);


if (cellrowidx &gt;= 0 &amp;&amp; cellcolidx &gt;= 0)


Dispatch.call (This.cell, "select");


}


/**


* Set the title of the current document


*


* @param title


* @param alignmenttype Alignment


* @see Setalignment


*/


public void Settitle (String title, int alignmenttype) {


if (title = NULL | | "". Equals (title))


Return


if (this.alignment = null)


This.getalignment ();


if (alignmenttype!= 0 &amp;&amp; alignmenttype!= 1 &amp;&amp; alignmenttype!= 2)


Alignmenttype = 0;


Dispatch.put (this.alignment, "alignment", alignmenttype);


Dispatch.call (this.selection, "TypeText", title);


}


/**


* Set the thickness of the current table border


*


* @param width


* Range: 1 &lt; W &lt; 13, if 0, on behalf of?] There are boxes &lt;br/&gt;


*/


public void settableborderwidth (int width) {


if (this.table = null)


Return


/*


* Set the table line Thickness 1: Represents the top one line 2: Represents the leftmost line 3: The bottom one line 4: The rightmost line 5: All horizontal lines except the top and bottom


* 6: All except the left and right side of the vertical bar 7: From the upper left to the lower right corner of the slash 8: from the bottom left to the upper right corner of the slash


*/


Dispatch borders = dispatch.get (table, "borders"). Todispatch ();


Dispatch border = null;


for (int i = 1; i &lt; 7; i++) {


border = Dispatch.call (borders, "Item", New Variant (i))


. Todispatch ();


if (width!= 0) {


Dispatch.put (Border, "LineWidth", new Variant (width));


Dispatch.put (Border, "Visible", New Variant (true));


else if (width = = 0) {


Dispatch.put (Border, "Visible", new Variant (false));


}


}


}


/**


* Get the value in the cell specified by the specified table


*


* @param tableindex


* Table index (starting from 1)


* @param rowIndex


* Row index (starting from 1)


* @param colindex


* Column index (starting from 1)


* @return


*/


Public String Gettxtfromcell (int tableindex, int rowIndex, int colindex) {


String value = "";


Set as current table


GetTable (Tableindex);


Getcell (RowIndex, Colindex);


if (cell!= null) {


Dispatch.call (Cell, "select");


Value = Dispatch.get (Selection, "Text"). ToString ();


Value = value.substring (0, Value.length ()-2); Remove the final return character;


}


return value;


}


/**


* Set bullets and lists for the currently selected content


*


* @param tabIndex


* &lt;ul&gt;


* &lt;li&gt;1. Project number &lt;/li&gt;


* &lt;li&gt;2. Number &lt;/li&gt;


* &lt;li&gt;3. Multilevel numbering &lt;/li&gt;


* &lt;li&gt;4. List style &lt;/li&gt;


* &lt;/ul&gt;


* @param index


* 0 means no, other numbers represent the first item in the tab page


*/


public void ApplyListTemplate (int tabIndex, int index) {


Get a list of ListGalleries objects


Dispatch listgalleries = Dispatch.get (This.word, "ListGalleries")


. Todispatch ();


Get an object in the list


Dispatch listgallery = Dispatch.call (ListGalleries, "Item",


New Variant (TabIndex)). Todispatch ();


Dispatch listtemplates = Dispatch.get (ListGallery, "ListTemplates")


. Todispatch ();


if (This.range = null)


This.getrange ();


Dispatch ListFormat = Dispatch.get (This.range, "ListFormat")


. Todispatch ();


Dispatch.call (ListFormat, "ApplyListTemplate"),


Dispatch.call (ListTemplates, "Item", New Variant (index)),


New Variant (TRUE), new variant (1), new variant (0));


}


/**


* Add Document Directory


*/


public void Addtablesofcontents () {


Get ActiveDocument, TablesOfContents, Range objects


Dispatch ActiveDocument = Word.getproperty ("ActiveDocument")


. Todispatch ();


Dispatch tablesofcontents = Dispatch.get (ActiveDocument,


"TablesOfContents"). Todispatch ();


Dispatch range = Dispatch.get (this.selection, Range). Todispatch ();


Add Directory


Dispatch.call (TablesOfContents, "Add", Range, new Variant (true),


The new Variant (1), the new variant (3), the new variant (TRUE), the new variant (


""), new variant (TRUE), new Variant (TRUE);


}


/**


* Set the current selection alignment


*


* @param alignmenttype


* &lt;ul&gt;


* &lt;li&gt;0 left &lt;/li&gt;


* &lt;li&gt;1. Center &lt;/li&gt;


* &lt;li&gt;2 Right &lt;/li&gt;


* &lt;/ul&gt;


*/


public void setalignment (int alignmenttype) {


if (this.alignment = null)


This.getalignment ();


Dispatch.put (this.alignment, "alignment", alignmenttype);


}


/**


* Get the current selection alignment


*


* @return Alignment


*/


Public Dispatch getalignment () {


if (this.selection = null)


This.getselection ();


This.alignment = Dispatch.get (this.selection, "ParagraphFormat")


. Todispatch ();


return this.alignment;


}


/**


* Get the Font object


*


* @return Font


*/


Public Dispatch GetFont () {


if (this.selection = null)


This.getselection ();


This.font = Dispatch.get (this.selection, "Font"). Todispatch ();


return this.font;


}


/**


* Set the current selection font


*


* @param fontname


* Font name, such as "Microsoft Ya Hei"


* @param isbold


* is bold


* @param isitalic


* Whether Italic


* @param isunderline


* Whether to underline


* @param rgbcolor


* Color value "1,1,1,1"


* @param Scale


* Font Spacing


* @param fontsize


* Font Size


*/


@Deprecated


public void Setfontscale (String fontname, Boolean isbold, Boolean isitalic,


Boolean isunderline, String rgbcolor, int Scale, int fontsize) {


Dispatch.put (This.font, "Name", FontName);


Dispatch.put (This.font, "Bold", isbold);


Dispatch.put (This.font, "Italic", isitalic);


Dispatch.put (This.font, "underline", isunderline);


Dispatch.put (This.font, "Color", RGBColor);


Dispatch.put (This.font, "scaling", Scale);


Dispatch.put (This.font, "Size", fontsize);


}








/**


* Set the font for the current selection


* @param whether the IsBold is bold


* @param whether the isitalic is italic


* @param Isunderline is underlined


* @param color RGB font colors For example: Red 255,0,0


* @param size Font 12: Small 416: Third


* @param name font names For example: XXFarEastFont-Arial, XXFarEastFont-Arial, italic, Arial


*/


public void SetFont (Boolean isbold,boolean isitalic,boolean isunderline,string color,string size,string name) {


Dispatch font = Dispatch.get (GetSelection (), "Font"). Todispatch ();


Dispatch.put (font, "name", new Variant (name));


Dispatch.put (font, "Bold", New Variant (IsBold));


Dispatch.put (Font, "Italic", New Variant (Isitalic));


Dispatch.put (font, "underline", new Variant (Isunderline));


if (! "". Equals (color))


Dispatch.put (font, "color", color);


Dispatch.put (font, "size", size);


}

/**


* Save File


*


* @param OutputPath


* Save Path


*/


public void SaveAs (String outputpath) {


if (this.document = null)


Return


if (OutputPath = null | | "". Equals (OutputPath))


Return


Dispatch.call (this.document, "SaveAs", OutputPath);


}


/**


* Save As HTML content


*


* @param htmlfile


* HTML file path


*/


public void saveashtml (String htmlfile) {


Dispatch.invoke (this.document, "SaveAs", Dispatch.method, new object[] {


Htmlfile, New Variant (8)}, new int[1]);


}


/**


* SaveFormat | Member name Description 0 | wdFormatDocument Microsoft Word


* format. 1 | wdFormatTemplate Microsoft Word template format. 2 |


* Wdformattext Microsoft Windows text format. 3 | Wdformattextlinebreaks


* Microsoft Windows text format with line breaks preserved. 4 |


* wdFormatDOSText Microsoft DOS text format. 5 | wdFormatDOSTextLineBreaks


* Microsoft DOS text with line breaks preserved. 6 | wdFormatRTF Rich Text


* Format (RTF). 7 | Wdformatencodedtext encoded text format. 7 |


* Wdformatunicodetext Unicode text format. 8 | wdformathtml Standard HTML


* format. 9 | Wdformatwebarchive WEB archive format. 10 |


* wdformatfilteredhtml filtered HTML format. 11 | Wdformatxml Extensible


* Markup Language (XML) format.


*/


/**


* Close the current Word document


*/


public void Close () {


if (document = = NULL)


Return


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


}


/**


* Execute the current document Print command


*/


public void Printfile () {


if (document = = NULL)


Return


Dispatch.call (document, "PrintOut");


}


/**


* Exit Microsoft Office Word Program


*/


public void Quit () {


Word.invoke ("Quit", new variant[0]);


Comthread.release ();


}





/**


* Select entire document


*/


public void Selectallcontent () {


Dispatch.call (this.document, "select");


}





/**


* Copy Entire document


* @param target


*/


public void copy () {


Dispatch.call (this.document, "select");


Dispatch.call (this.selection, "copy");


}





/**


* Paste the selection at the current insertion point position


*/


public void paste () {


Dispatch.call (this.selection, "paste");


}





public static void Main (string[] args) throws IOException {


Msofficegeneratorutils officeutils = new Msofficegeneratorutils (true);


Officeutils.opendocument ("D:\TRS\TRSWCMV65HBTCIS\Tomcat\webapps\wcm\eipv65\briefreport\templates\zhengfa\ Head. doc ");


Officeutils.replaceall ("${briefreport_year}", "2011");


Officeutils.replaceall ("${briefreport_issue}", "3");


File File = File.createtempfile ("Test", ". tmp");


System.out.println (File.getabsolutepath ());


File.delete ();


File File = new file ("C:\docume~1\admini~1\locals~1\temp\test5411720146039914615.tmp");


System.out.println (File.exists ());





Officeutils.createnewdocument ();


Officeutils.createnewtable (1, 1, 1);


Officeutils.inserttext ("Published time: 2011-11-11");


Officeutils.moveright (1);


Officeutils.inserttext ("T");


Officeutils.moveright (1);


Officeutils.inserttext ("Channel: Macro Environment/social environment");


Officeutils.moveright (1);


Officeutils.inserttext ("T");


Officeutils.moveright (1);


Officeutils.inserttext ("article Author: Yang Yemao");


Officeutils.moveright (1);


Officeutils.inserttext ("I ' m Chinese");


Officeutils.moveright (1);


Officeutils.enterdown (1);


Officeutils.inserttext ("I ' m not Chinese");


Officeutils.moveright (1);








/* Doc2 = Dispatch.call (documents, "Open", Anotherdocpath). Todispatch ();


Dispatch paragraphs = dispatch.get (doc2, "paragraphs"). Todispatch ();


Dispatch paragraph = dispatch.call (paragraphs, "Item", New Variant (Paragraphindex)). Todispatch ();





Officeutils.setfontscale ("Microsoft Ya-Black", true, True, true, "1,1,1,1", 100,


18);


Officeutils.setalignment (1);


Officeutils.inserttotext ("This is a Test");


Officeutils.moveend ();


Officeutils.setfontscale ("Microsoft Ya-Black", false, False, False, "1,1,1,1", 100,


18);


Officeutils.insertimage ("d:\11.jpg");


Officeutils.enterdown (1);


Officeutils.inserttotext ("This is my Photo");


Officeutils.enterdown (1);


Officeutils.createnewtable (3, 5, 1);


list&lt;string[]&gt; list = new arraylist&lt;string[]&gt; ();


for (int i = 0; i &lt; 3; i++) {


string[] STRs = new STRING[5];


for (int j = 0; J &lt; 5; J + +) {


STRS[J] = j + i + "";


// }


List.add (STRs);


// }


Officeutils.inserttotable (list);


Officeutils.createnewtable (10, 10, 1);


Officeutils.moveend ();


Officeutils.enterdown (1);


Officeutils.createnewtable (3,2,1);


Officeutils.mergecell (1, 1, 7, 1, 9);


Officeutils.mergecell (1, 2, 2, 3, 7);


Officeutils.mergecell (1, 3, 4, 9, 10);


Officeutils.inserttext ("123");


Officeutils.getcell (1, 2);


Officeutils.splitcell (2, 4);


Officeutils.selectcell (1, 2);


Officeutils.inserttext ("split");


Officeutils.selectcell (1, 5);


Officeutils.inserttext ("Split1");


Officeutils.selectcell (1, 6);


Officeutils.inserttext ("yy");


Officeutils.selectcell (2, 4);


Officeutils.inserttext ("LTG");


Officeutils.saveas ("D:\" + system.currenttimemillis () + ". Doc");


Officeutils.close ();


Officeutils.quit ();


}


}


Testjsoupcomponent


Package com.topstar.test;


Import Java.io.File;


Import Java.io.FileWriter;


Import java.io.IOException;


Import java.util.ArrayList;


Import Java.util.HashMap;


Import java.util.List;


Import Java.util.Map;


Import Java.util.Map.Entry;


Import Java.util.UUID;


Import Org.jsoup.Jsoup;


Import org.jsoup.nodes.Document;


Import org.jsoup.nodes.Element;


Import Org.jsoup.nodes.Node;


Import com.eprobiti.trs.TRSException;


/** * Basic idea: Get HTML content, because nonstandard HTML content, use the Jsoup component to convert the content that reads out to the standard HTML file content,


* Then iterate over each node, find the IMG tag, record its index, and then according to its filename rules stitching out the physical path of the picture, replace it with ${image_index} identity, and then {index, PATH}


* In the form of a key-value pair to the map, such as


* "${image_1,d:lucene.png}" format, then use the Jacob component to open the Template.doc, select the entire document and copy, and then create a new document, paste just copied inside


* Find a picture ID, replace it with a picture


*


* @since 2011-12-09


* @author Xioawu


* @cateogry Topstar


* @version 1.0


*/


public class Testjsoupcomponent {


private static document document;


private static map&lt;string, string&gt; Imgmap = new hashmap&lt;string, string&gt; (); Store picture identifiers and physical paths i.e {"image_1", "D:\lucene.png"};


private static list&lt;string&gt; files = new arraylist&lt;string&gt; (); File name of the local generated article doc


private static Integer Imgindex = 1; Picture ID


public static void Main (string[] args) throws Trsexception, IOException {


Msofficegeneratorutils officeutils = new Msofficegeneratorutils (true); To set the build process to invisible





String html = "&lt;html&gt;.....&lt;/html&gt;";//Get body content, fill in HTML content yourself here


String Header = "Test title"; Get the article title


Document = Jsoup.parse (HTML);


System.out.println (document.html ());


For (Element element:document.body (). Select (' Body &gt; * '))


Recursively iterate through all the direct child elements under the body, find the IMG tag, @see Syselementtext method


Syselementtext (Element);


File File = new file ("D:" + file.separator + "Template.doc");


File.createnewfile (); Create template HTML


FileWriter FW = new FileWriter (file);


Fw.write (document.html (), 0, document.html (). Length ());//write file


Fw.flush (); Empty FileWriter Buffer


Fw.close ();


Officeutils.opendocument ("D:\template.doc"); Open Template.doc. template.doc files generated by Dochtmlcon in the Trsserver eipdocument library


Officeutils.copy (); Copy entire document


Officeutils.close ();


Officeutils.createnewdocument ();


Officeutils.paste (); Paste Entire Document


For (entry&lt;string, string&gt; entry:imgMap.entrySet ())//loop to replace the picture ID bit with a picture


Officeutils.replacetext2image (Entry.getkey (), Entry.getvalue ());


Officeutils.movestart (); Move the insertion point to the top of the Word document


Officeutils.setfont (True, False, False, "0,0,0", "20", "Arial"); Set the font, specific parameters, see the API yourself


Officeutils.settitle (header, 1); Set Title


Officeutils.enterdown (1); Set line return


String filename = Uuid.randomuuid (). toString ();


Files.add (filename); Record file name,


Officeutils.saveas ("D:" + file.separator + filename + ". doc"); Generates D:\UUID.doc files, using UUID to prevent the same name


Officeutils.close (); Close documents created by Office Word


Officeutils.quit (); Quit Office Word programs


Msofficegeneratorutils msofficeutils = new Msofficegeneratorutils (false); The consolidation process is set to visible


Msofficeutils.createnewdocument ();


Msofficeutils.saveas ("D:" + file.separator + "Complete.doc");


Msofficeutils.close ();


for (String filename:files) {


Msofficeutils.opendocument ("D:" + file.separator + fileName + ". Doc");


Msofficeutils.copy ();


Msofficeutils.close ();


Msofficeutils.opendocument ("D:" + file.separator + "Complete.doc");


Msofficeutils.moveend ();


Msofficeutils.enterdown (1);


Msofficeutils.paste ();


Msofficeutils.saveas ("D:" + file.separator + "Complete.doc");


Msofficeutils.close ();


}


Copy a *.doc document with less content to prevent the word program from being prompted with a large amount of copy content in memory, and whether it should be applied to another Program dialog box.


Msofficeutils.createnewdocument ();


Msofficeutils.inserttext ("test message");


Msofficeutils.copy ();


Msofficeutils.close ();


Msofficeutils.quit ();


Imgindex = 1;


Imgmap.clear ();


}


public static void Syselementtext (node node) {


if (Node.childnodes (). Size () = 0) {


if (Node.nodename (). Equals ("img")) {//Handling picture path problems


Node.after ("&lt;p&gt;${image_" + Imgindex + "}&lt;/p&gt;"); Add a sibling P tag for IMG, Content &lt;P&gt;${image_imgIndexNumber}&lt;/P&gt;


String src = node.attr ("src");


Node.remove (); Remove the IMG tag.


StringBuffer Imgurl = new StringBuffer ("D:\TRS\TRSWCMV65HBTCIS\WCMData\webpic\"); To temporarily write the path directly to death, the formal application should be rewritten here as a Webpic configuration item


Imgurl.append (src.substring (0, 8)). Append ("\"). Append (src.subsequence (0)). Append ("\"). Append (SRC);


Node.attr ("src", imgurl.tostring ()); This is not necessary because the IMG tag has been removed


Imgmap.put ("${image_" + imgindex++ + "}", imgurl.tostring ());


}


} else {


For (Node rNode:node.childNodes ()) {


Syselementtext (Rnode);


}


}


}


}


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.