Java exporting Word with Freemarker

Source: Internet
Author: User

A recent project to export Word documents, toss long time, find or use Freemarker template to make more convenient. Now summarize the key steps. For your reference, here is a simple sample of the test paper generation.

First, the production of templates

First use Word to make a template, for example:

(Note that there is a table above, I set the border is not visible) and then save as an XML file, and then open the XML file with a tool, someone with Firstobject XML editor feel is not as good as notepad++. I use notepad++ here, mainly have highlighted, and the elements themselves actively paired, effects such as the following:

Above the black place is basically the place we want to replace, for example Xytitle replaced with ${xytitle}, for the table to be very careful, for example, the selection of the table below, we can <w:tr> find to locate, a pair of <w:tr></w: Tr> represents a row, that is, a record (a problem), we have to use a pair of < #list ></> to include it, in order to possibly fill the data, detailed can refer to Freemarker page syntax, such as the choice of the topic here. We are a record of two behaviors, so to < #list ></#list > To include two lines, shaped like:< #list table1 as plan1><w:tr> question number </w:tr><w :tr> option </w:tr></#list, and then find the corresponding xzn,xztest,ans1 in this. Ans2,ans3,ans4 replaced by ${plan1.xzn},${plan1.xztest}. ${PLAN1.ANS1},${PLAN1.ANS2},${PLAN1.ANS3},${PLAN1.ANS4}, notice here the Table1 and plan1 named. Table1 might fill in the data to use, the other substitution of the same operation, get the effect such as the following:

After saving, change the suffix name to FTL. This completes the template.

Second, the realization of programming

The Freemarker-2.3.13.jar bag is used here. The code is as follows:

Package Common;import Java.io.bufferedwriter;import Java.io.file;import java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.outputstreamwriter;import Java.io.unsupportedencodingexception;import Java.io.writer;import Java.util.map;import Freemarker.template.configuration;import Freemarker.template.template;import Freemarker.template.templateexception;public class Documenthandler {private Configuration Configuration = Null;public Documenthandler () {configuration = new configuration (); Configuration.setdefaultencoding ("Utf-8");} public void Createdoc (map<string,object> datamap,string fileName) throws Unsupportedencodingexception {// DataMap to fill in the Modeled data File//Set modeled device method and path, Freemarker support a variety of template loading methods.

Ability to re-servlet. CLASSPATH, database load,//Here Our templates are placed in the template package below configuration.setclassfortemplateloading (This.getclass (), "/template"); Template T=null;try {//TEST.FTL) is the stencil to be loaded t = configuration.gettemplate ("FCTESTPAPER.FTL");} catch (IOException e) { E.printstacktrace ();} Output document path and name file OutFile = new file (fileName); Writer out = null; FileOutputStream fos=null;try {fos = new FileOutputStream (outFile); OutputStreamWriter owriter = new OutputStreamWriter ( FOS, "UTF-8");//The local convection coding is indispensable. It should be possible to invoke it separately with main (), but suppose the Word document will not open when the Web request is exported and the package XML file is wrong. The main thing is that the encoding format is incorrect. cannot be resolved. out = new BufferedWriter (new OutputStreamWriter (New FileOutputStream (OutFile))); out = new BufferedWriter (owriter); } catch (FileNotFoundException E1) {e1.printstacktrace ();} try {t.process (dataMap, out); Out.close (); Fos.close ();} catch (Templateexception e) {e.printstacktrace ();} catch ( IOException e) {e.printstacktrace ();} System.out.println ("---------------------------");}}

Then you prepare the data call. The code is as follows:

Package Com.havenliu.document;import Java.io.unsupportedencodingexception;import Java.util.arraylist;import Java.util.hashmap;import Java.util.list;import Java.util.map;public class Main {/** * @param args * @throws Unsupporteden Codingexception */public static void Main (string[] args) throws unsupportedencodingexception {; map<string, object> dataMap = new hashmap<string, object> ();d atamap.put ("Xytitle", "quiz paper"); int index = 1;//selection question list<map<string, object>> list1 = new arraylist<map<string, object>> ();//Topic list<map< String, object>> list11 = new arraylist<map<string, object>> ();//Answer index = 1;for (int i = 0; i < 5; I + +) {map<string, object> Map = new hashmap<string, object> (); Map.put ("Xzn", Index + "."); Map.put ("Xztest", "() operating system agrees to connect multiple terminals at the same time on a single host." Multiple users can interact with the computer at the same time through their respective terminals. Map.put ("ans1", "A" + Index), map.put ("Ans2", "B" + Index), map.put ("Ans3", "C" + Index), map.put ("Ans4", "D" + index); Lis T1.add (map); Map<striNg, object> map1 = new hashmap<string, object> (); Map1.put ("Fuck", Index + "."); Map1.put ("abc", "A" + index); List11.add (MAP1); index++;} Datamap.put ("table1", List1);d atamap.put ("Table11", list11);//fill in the blanks list<map<string, object>> list2 = new Arraylist<map<string, object>> (); list<map<string, object>> list12 = new arraylist<map<string, object>> (); index = 1;for (int i = 0; I < 5; i++) {map<string, object> Map = new hashmap<string, object> (); Map.put ("tkn", Index + "."); Map.put ("Tktest", "Operating system" is an ___ system software _______ in a computer system. It manages and controls the ___ resource _________ in the computer system. "); List2.add (map); map<string, object> map1 = new hashmap<string, object> (); Map1.put ("Fill", Index + "."); Map1.put ("def", "Intermediate dispatch" + index); List12.add (MAP1); index++;} Datamap.put ("Table2", List2);d atamap.put ("Table12", list12);//Inference topic list<map<string, object>> list3 = new Arraylist<map<string, object>> (); list<map<string, object>> list13 = newArraylist<map<string, object>> (); index = 1;for (int i = 0; i < 5; i++) {map<string, object> Map = new Hashmap<string, Object> (), Map.put ("PDN", Index + "."); Map.put ("Pdtest", "Compound firewall firewall is the isolation point of the intranet and the external network, plays the role of monitoring and isolating the application layer communication flow, also often combines the function of the filter at the same time." "); List3.add (map); map<string, object> map1 = new hashmap<string, object> (); Map1.put ("Judge", Index + "."); Map1.put ("Hij", "pair" + index); List13.add (MAP1); index++;} Datamap.put ("Table3", List3);d atamap.put ("Table13", list13);//simple answer list<map<string, object>> list4 = new Arraylist<map<string, object>> (); list<map<string, object>> list14 = new arraylist<map<string, object>> (); index = 1;for (int i = 0; I < 5; i++) {map<string, object> Map = new hashmap<string, object> (); Map.put ("Jdn", Index + "."); Map.put ("Jdtest", "description job schedule.") Intermediate scheduling and process scheduling differences, and analysis of the following issues should be responsible for the level of dispatcher. "); List4.add (map); map<string, object> map1 = new hashmap<string, object> (); Map1.put ("Answer", Index + ".");Map1.put ("XYZ", "describes the difference between job scheduling, intermediate scheduling, and process scheduling, and analyzes which level of scheduler is responsible for the following issues.") "); List14.add (MAP1); index++;} Datamap.put ("Table4", List4);d atamap.put ("Table14", list14); MDoc MDoc = new MDoc () Mdoc.createdoc (DataMap, "E:/outfile.doc");}}

Note that the key in the map above must correspond with the template, otherwise it will be an error. Effects such as the following:


Freemarker page Syntax: http://blog.csdn.net/thismonth/article/details/5194982

Demo sample Code and Documentation: http://download.csdn.net/detail/wangqiuyun/7373817

Reprint Please specify source: http://blog.csdn.net/wangqiuyun/article/details/26348819

Java exporting Word with Freemarker

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.