Using templates to export Files (ii) Jacob use Word templates to export Word files (java2word)

Source: Internet
Author: User
Tags save file

Download the Jacob.jar package first.

After decompression, place the jacob.dll below windows/system32 or below \jre\bin.

Add Jacob.jar to the project.

The environment of the project is basically finished, and the next step is to write the relevant code:

/*** the incoming data is a HashMap object, and the key in the object represents the field to be replaced in the Word template. Value represents the values to replace. * All fields to be replaced in the Word template (that is, key in HashMap) begin and end with special characters. * such as: $code $, $date $ ..... To avoid performing an incorrect replacement.

* All the fields to be replaced with the picture, the key must include the image or value as the full path of the picture * (now only infer the file suffix named:. bmp,. jpg,. gif).

* In order to replace the data in the table, the key format in HashMap is "[email protected]", in which: * R represents the beginning of the first row of the table, and N represents the nth table in the Word template; * value is the ArrayList object, The objects included in ArrayList are unified as string[], and a string[] represents a row of data. * The first record in ArrayList is a special record. The record is the column number to be replaced in the table, such as: To replace the first column, the second column, the third column of data. The first record is string[3] {"1", "2", "3"}. */import Java.util.arraylist;import Java.util.hashmap;import Java.util.iterator;import Com.jacob.activex.activexcomponent;import Com.jacob.com.dispatch;import com.jacob.com.variant;/** * Use Word templates to generate Word files * @typename: Java2word * @author: Fishroad * @since: August 24, 2015 PM 2:47:41 * */public class Java2word { Private Boolean saveonexit; /** * Word Document * */Dispatch doc = null; /** * Word Execution Program Object S */private activexcomponent word; /** * All Word documents */private Dispatch documents; /** * constructor */public Java2word () {if (word==null) {word = new Activexcomponent ("Word.applica tion "); Word.setproperty ("Visible", new Variant (false)); } IF (documents==null) documents = Word.getproperty ("Documents"). Todispatch (); Saveonexit = false; }/** * Set parameters: Whether to save on Exit * @param saveonexit boolean true-save file when exiting, false-do not save file on exit */public void Set Saveonexit (Boolean saveonexit) {this.saveonexit = Saveonexit; /** * Gets the number of references: whether to save when exiting @return Boolean true-to save the file when exiting, false-to exit without saving the file */public boolean getsaveonexit ( ) {return saveonexit; /** * Open File * @param inputdoc String to open file, full path * @return Dispatch Open File */public Dispat CH Open (String inputdoc) {return Dispatch.call (documents, "open", Inputdoc). Todispatch (); /** * Selection * @return Dispatch selected range or insertion point */public Dispatch Select () {return word.get Property ("Selection"). Todispatch (); /** * Move the selection or insertion point up * @param selection Dispatch What to move * @param the distance that count int moves */publi c void MoveUp (Dispatch sElection,int count) {for (int i = 0;i < Count;i + +) Dispatch.call (selection, "MoveUp"); /** * Move the selection or insertion point down * @param selection Dispatch What to move * @param the distance that count int moves */publi c void MoveDown (Dispatch selection,int count) {for (int i = 0;i < Count;i + +) Dispatch.call (selecti On, "MoveDown"); /** * Move the selection or insertion point to the left * @param selection Dispatch What to move * @param the distance that count int moves */publi c void MoveLeft (Dispatch selection,int count) {for (int i = 0;i < Count;i + +) {Dispatch.call (Selec tion, "MoveLeft"); }}/** * Move the selection or insertion point to the right * @param selection Dispatch What to move * @param the distance that count int moves */ public void MoveRight (Dispatch selection,int count) {for (int i = 0;i < Count;i + +) Dispatch.call ( Selection, "MoveRight"); /** * Move the insertion point to the first position of the file * @param selection Dispatch insertion point */ public void MoveStart (Dispatch selection) {Dispatch.call (Selection, "HomeKey", New Variant (6)); /** * Start finding text from the selection or insertion point * @param selection Dispatch selection * @param tofindtext String text to find * @ Return Boolean true-Find and select the text. false-not found text */public boolean find (Dispatch selection,string tofindtext) {//Start query from selection location Dispatch find = Word.call (selection, "find"). Todispatch (); Set what to look for Dispatch.put (Find, "Text", Tofindtext); Look forward dispatch.put (Find, "Forward", "True"); Set format dispatch.put (Find, "format", "True"); Uppercase and lowercase matches dispatch.put (find, "matchcase", "True"); Whole word match dispatch.put (find, "MatchWholeWord", "True"); Find and select Return Dispatch.call (Find, "Execute"). Getboolean (); }/** * Replace selection with set text * @param selection Dispatch selection * @param newtext String to text */pub LIC void replace (Dispatch Selection,strinG NewText) {//Set alternate text dispatch.put (selection, "text", NewText); }/** * Global replace * @param selection Dispatch selection or starting insertion point * @param oldtext String text to replace * @param NE Wtext String is replaced with text */public void ReplaceAll (Dispatch selection,string oldtext,object replaceobj) {//moved to File at the beginning of MoveStart (selection); if (Oldtext.startswith ("table") | | | replaceobj instanceof ArrayList) replacetable (Selection,oldtext, (ArrayList) Replaceobj); else {String NewText = (string) replaceobj; if (newtext==null) newtext= ""; if (Oldtext.indexof ("image")! = -1&!newtext.trim (). Equals ("") | | Newtext.lastindexof (". bmp")! =-1 | | Newtext.lastindexof (". jpg")! =-1 | | Newtext.lastindexof (". gif")! =-1) {while (Find (Selection,oldtext)) {Replaceimage (Sele Ction,newtext); Dispatch.call (Selection, "MoveRight"); }}else{while (Find (Selection,oldtext)) {replace (selection,newtext); Dispatch.call (Selection, "MoveRight"); }}}}/** * Replace picture * @param selection Dispatch image insertion point * @param imagePath St Ring picture file (full path) */public void Replaceimage (Dispatch selection,string imagePath) {Dispatch.call (Dispatch. Get (Selection, "InlineShapes"). Todispatch (), "AddPicture", ImagePath); }/** * Replace table * @param selection Dispatch insertion point * @param tableName String table name. * shaped like [email protected], [email protected][email protected]. The r represents starting with the nth row in the table, and n is the nth table in the Word file * @param the corresponding table of fields and data to be replaced in the field HASHMAP table */public void replacetable (DISPATC H selection,string tablename,arraylist dataList) {if (Datalist.size () <= 1) {System.out.println ("E Mpty table! "); Return }//Columns to populate String[] cols = (string[]) datalist.get (0); Table ordinal String tbindex = tablename.substring (Tablename.lastindexof ("@") + 1); Starting from the first few lines, populate int fromrow = Integer.parseint (tablename.substring (Tablename.lastindexof ("$") + 1,tablename.lastindexof ("@"))); All tables Dispatch tables = Dispatch.get (doc, "Tables"). Todispatch (); The table to populate Dispatch table = Dispatch.call (tables, "Item", New Variant (Tbindex)). Todispatch (); All rows of the table Dispatch rows = dispatch.get (table, "Rows"). Todispatch (); Fill table for (int i = 1;i < Datalist.size (); i + +) {//a row of data string[] Datas = (string[]) da Talist.get (i); Add a row to the table if (Dispatch.get (rows, "Count"). GetInt () < Fromrow + i-1) dispatch.call (rows, "Ad D "); Populate the row for the related column for (int j = 0;j < Datas.length;j + +) {//Get cell Dispatch cells = D Ispatch.cAll (table, "Cell", integer.tostring (Fromrow + i-1), Cols[j]). Todispatch (); Select cell Dispatch.call (cell, "select"); Set the format Dispatch font = dispatch.get (selection, "Font"). Todispatch (); Dispatch.put (font, "Bold", "0"); Dispatch.put (font, "Italic", "0"); Input data Dispatch.put (selection, "Text", Datas[j]); }}}/** * Save file * @param outputPath String output file (including path) */public void Save (String o Utputpath) {Dispatch.call (Dispatch.call (Word, "WordBasic"). Getdispatch (), "FileSaveAs", OutputPath); }/** * Close file * @param document Dispatch file to close */public void Close (Dispatch doc) {Dis Patch.call (Doc, "Close", New Variant (Saveonexit)); Word.invoke ("Quit", New variant[]{}); Word = null; /** * Create Word file based on template, data * @param inputpath String template file (including path) * @param oUtpath string output file (including path) * @param data HASHMAP packet (including fields to be populated, corresponding data) */public void Toword (string inputpath,st Ring Outpath,hashmap data) {String oldtext; Object NewValue; try {if (doc==null) doc = open (InputPath); Dispatch selection = select (); Iterator keys = Data.keyset (). Iterator (); while (Keys.hasnext ()) {OldText = (String) keys.next (); NewValue = Data.get (OldText); ReplaceAll (Selection,oldtext,newvalue); } save (Outpath); } catch (Exception e) {System.out.println ("Operation Word file failed! "); E.printstacktrace (); } finally {if (doc! = null) close (DOC); }} public synchronized static void Word (String inputpath,string outpath,hashmap data) {Java2word j2w = new Java2word (); j2w.toword (Inputpath,outpath,data); } @SuppressWarnings ({"Rawtypes", "Unchecked"}) public static void main (string[] args) {//Replace related fields in Word HashMap data = new HashMap (); Data.put ("$reportDept $", "2007-8-1"); Data.put ("$findDate $", "2007-8-2"); Data.put ("$finder $", "KDL"); Data.put ("$lineName $", "line Line 5"); Data.put ("$voltageRate $", "November 13"); Data.put ("$towerNumberBound $", "November 10, 2004"); Data.put ("$image 1$", "c:\\users\\administrator\\pictures\\1.jpg"); Data.put ("$name $", "fishroad"); Data.put ("$age $", "24"); Replace the data in a table in Word/** * In order to replace the data in the table, the key format in HashMap is "[email protected]", in which: * R represents starting from the first row of the table, n represents The nth table in the Word template; * value is a ArrayList object, and the objects included in the ArrayList are unified to string[]. * One string[] represents a row of data, and the first record in ArrayList is a special record. The column number to be replaced in the table is recorded. * For example, to replace the first column, the second column, the third column of data, the first record is string[3] {"1", "2", "3"} */ArrayList table1 = new ArrayList (3); String[] FieldName1 = {"1", "2", "3"}; Table1.add (FIELDNAME1); String[] Field11 = {"1", "751002", "Huaxia Securities"}; Table1.add (FIELD11); String[] Field21 = {"2", "751004", "Guotai Junan"}; Table1.add (FIELD21); String[] field31 = {"3", "751005", "Haitong Securities"}; Table1.add (FIELD31); Data.put ("[email protected]", table1); Java2word j2w = new Java2word (); Long time1 = System.currenttimemillis (); J2w.toword ("E:/template.doc", "E:/result.doc", data); System.out.println ("Time Cost:" + (System.currenttimemillis ()-time1)); }}

The above is the relevant code. Next you will configure the Word template, for example the following:

The results of the export are for example:


Using templates to export Files (ii) Jacob use Word templates to export Word files (java2word)

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.