Use Java to quickly build Word documents

Source: Internet
Author: User

When we use Java to build Word documents, we usually think of itext and poi first, because we are used to using these two methods to manipulate Excel, and we naturally want to use this to build Word documents. But when we need to dynamically build word, we usually have to be able to not only display the content in Word, but also keep the complex styles in Word very well. Then if you use Itext and poi to operate, it is like a programmer to move bricks as painful.

At this point, we should consider using Freemarker template technology to quickly implement this complex function, so that programmers in the process of drinking coffee to solve the problem. The idea is to create a Word document, fill a template in Word as required, then change the corresponding data into a variable ${}, then save the document as an XML document format, use the document editor to open the XML format document, and remove the extra XML symbol, Use Freemarker to read the document and then replace the variable to output the Word document.

The specific process is as follows:

1. Create a formatted Word document that replaces the data that needs to be displayed dynamically with a variable character.


2. Save the Word document you just created as an XML format.


3. Edit this XML document to remove the extra XML tags, such as the blue part of the figure


4. Download the latest development package from Freemarker's official website and copy Freemarker.jar to your development project.

5. Create a new Docutil class to implement a method for generating Word files based on doc templates

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 Word file according to Doc template * @param datamap Map needs to fill in the template data * @param fileName file name * @param savepath Save path */publicvoid Createdoc (map<string, object> datamap, String Downloadtype, St
                     Ringsavepath) {try{//load the template that needs to be loaded templatetemplate = null;
              Load Template file       Configure.setclassfortemplateloading (This.getclass (), "/com/favccxx/secret/templates");
                     Set Object wrapper Configure.setobjectwrapper (Newdefaultobjectwrapper ());
                     Set exception handler Configure.settemplateexceptionhandler (Templateexceptionhandler.ignore_handler); Define the template object, note that the template type name is consistent with Downloadtype template= configure.gettemplate (Downloadtype + ". x
                    
                     ML ");
                     Output document 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. The user invokes the variable that needs to be passed by using Getdatamap, and then calls the Createdoc method to generate the required document, as needed.

/**
 * Get the MAP parameter to pass 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 object to Map * @param obj object class * @return/public static map<string,object> Setobjtomap (Object obj) {C
		Lass 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 ("The" is: "+ method);
					if (Method.startswith ("get")) {Object value = Methods[i].invoke (obj);
						if (value!= null) {if (Value.getclass (). getClassLoader ()!= null) {//Handle 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. Quickly apply this method to your project.

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.