Use Java to generate WORD Documents (with source code)

Source: Internet
Author: User

When we use Java to generate WORD Documents, we usually first think of iText and POI. This is because we are used to using these two methods to Operate Excel, and naturally want to use this to generate WORD Documents. However, when we need to dynamically generate a word, we usually not only need to be able to display the content in the word, but also be able to maintain the complex style in the word. At this time, if you use IText and POI again, it is as painful as a programmer to move bricks.


At this time, we should consider using FreeMarker's template technology to quickly implement this complex function, so that programmers can solve the problem while drinking coffee. The implementation idea is as follows: first create a word document, fill in a template in word as needed, then replace the corresponding data with the variable $ {}, and then save the document as an xml document format, open the document in xml format in the document Editor, remove unnecessary xml characters, use Freemarker to read the document, replace the variable, and output the Word document.

The specific process is as follows:

1. Create a formatted Word document and replace the data to be dynamically displayed with a variable character.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1229442547-0.png "title =" Java generate wordfile 01.png "alt =" 1401_908.png"/>

2. Save the created Word document as xml.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/122944M02-1.png "title =" Java generate wordfile 02.png "alt =" 140752129.png"/>


3. Edit this XMl document to remove unnecessary xml tags, in the blue section

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/1229444152-2.png "title =" javause freemarkerto generate wordfile 03.png "alt =" 140826202.png"/>



4. Download Freemarker from its official website. Copy freemarker. jar to your own development project.

5. Create a DocUtil class to generate a word file based on the Doc template.

Package com. favccxx. secret. util; import java. io. bufferedWriter; import java. io. file; import java. io. fileOutputStream; import java. io. outputStreamWriter; import java. io. writer; import java. util. map; import freemarker. template. configuration; import freemarker. template. defaultObjectWrapper; import freemarker. template. template; import freemarker. template. templateExceptionHandler; public class DocUtil {privateConfiguration configure = null; publicDocUtil () {configure = new Configuration (); configure. setDefaultEncoding ("UTF-8 ");} /*** generate the word file according to the Doc template * @ param dataMap Map: Enter the template data * @ param fileName file name * @ param savePath save path */publicvoid createDoc (Map <String, object> dataMap, String downloadType, StringsavePath) {try {// load the template Templatetemplate to be loaded = null; // load the template file configure. setClassForTemplateLoading (this. getClass (), "/com/favccxx/secret/templates"); // set the configure of the object packer. setObjectWrapper (newDefaultObjectWrapper (); // sets the configure of the exception processor. setTemplateExceptionHandler (TemplateExceptionHandler. IGNORE_HANDLER); // defines the Template object. Note that the template type name and downloadType must be consistent with Template = configure. getTemplate (downloadType + ". xml "); // output File FileoutFile = new File (savePath); Writerout = null; out = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (outFile)," UTF-8 ")); template. process (dataMap, out); outFile. delete ();} catch (Exception e) {e. printStackTrace ();}}}

6. You can call getDataMap to obtain the variables to be passed based on your needs, and then call the createDoc method to generate the required documents.

/*** Obtain the Map parameter to be passed according to the download type * @ param oid Object Id * @ param downloadType download type */private Map <String, Object> getDataMap (String oid, string downloadType) {Map <String, Object> dataMap = new HashMap <String, Object> (); if ("Parameter1 ". equals (downloadType )){...... dataMap = DataMapUtil. setObjToMap (Object1);} else {...... dataMap = DataMapUtil. setObjToMap (Object2);} return dataMap ;}

  

  

Public class DataMapUtil {private static Map <String, Object> dataMap = new HashMap <String, Object> (); /*** convert the Object to Map * @ param obj Object Class * @ return */public static Map <String, Object> setObjToMap (Object obj) {Class c; try {c = Class. forName (obj. getClass (). getName (); Method [] methods = c. getMethods (); for (int I = 0, l = methods. length; I <l; I ++) {String method = methods [I]. getName (); System. out. println ("Th E method is: "+ method); if (method. startsWith (" get ") {Object value = methods [I]. invoke (obj); if (value! = Null) {if (value. getClass (). getClassLoader ()! = Null) {// process the custom object type setObjToMap (value);} String key = method. substring (3); key = key. substring (0, 1 ). toLowerCase () + key. substring (1); if ("java. util. date ". equals (value. getClass (). getName () {value = DateUtil. dateToString (Date) value);} dataMap. put (key, value) ;}}} catch (Exception e) {e. printStackTrace ();} return dataMap ;}}


7. apply this method to your project.


This article from the "dust wind with the shadows of the Sky" blog, please be sure to keep this source http://genuinecx.blog.51cto.com/2890523/1331115

Related Article

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.