Use Freemarker to export word for others to download

Source: Internet
Author: User
Tags locale

The company does project need a function, request as follows,

Export a list of eligible lists to Word for others to download.

Start to use POI to do the action table, reasoning, not familiar with this,

Also want to use Jacob to operate, also not very ideal, on Google's one, found


Write the article, feel good, so wrote a demo, as a code of the set tired bar.

At the same time, also thank the author of the document.

Examples are written in combination with struts2, and Word template files are saved in MHT format.

The code is as follows: The structure diagram is as follows:   is mainly used to generate Word files package com.jr.cont; Import; Import; Import; Import; Import; Import; Import; Import Java.util.Locale; Import Java.util.Map; Import Org.apache.struts2.ServletActionContext; Import freemarker.template.Configuration; Import Freemarker.template.Template; Import freemarker.template.TemplateException; /** use Freemarker to generate word */public class Staticfreemarker {/*** * @param FTL template name * @param htmlname name after word * @param map Data collection Map * @param fileName folder name * @throws IOException * @throws templateexception */public void init (string FTL, String HTMLName, map map, String FileName) throws IOException, templateexception {Configuration freemarkercfg = new Configuratio N (); Freemarkercfg.setservletcontextfortemplateloading (Servletactioncontext.getservletcontext (), "/" + fileName); Freemarkercfg.setencoding (LOcale.getdefault (), "GBK"); Template Template; Template = Freemarkercfg.gettemplate (FTL); Template.setencoding ("GBK"); String path = Servletactioncontext.getservletcontext (). Getrealpath ("/"); SYSTEM.OUT.PRINTLN (path); BufferedWriter buff = new BufferedWriter (new FileWriter (path + htmlname)); File Htmlfile = new file (path + htmlname); Writer out = new BufferedWriter (new OutputStreamWriter (New FileOutputStream (Htmlfile), "GBK")); Template.process (map, out); Buff.close (); Out.flush (); Out.close ();  exportwordaction for page Request generation event package Com.jr.cont; Import; Import java.util.ArrayList; Import Java.util.HashMap; Import java.util.List; Import Java.util.Map; Import Com.opensymphony.xwork2.ActionSupport; Import freemarker.template.TemplateException; /** generates word's action*/public class Exportwordaction extends Actionsupport {private static final long Serialversionuid = 793 4795621981455907L; @SuppressWarnings ("unchecked") @Override public String execute () {StaticfreemarKer SF = new Staticfreemarker (); list<target> Target = new arraylist<target> (); Target tar; /** assumed data */for (int i=1;i<=100;i++) {tar= new Target (); Tar.setid (i); Tar.setname1 ("name" +i); Tar.setname2 ("name" +i); Tar.setname3 ("name" +i); Tar.setname4 ("name" +i); Tar.setname5 ("name" +i); Target.add (TAR); The map map = new HashMap (); Map.put ("list", target); String htmlfile2 = "Data report. Mht.doc"; try {sf.init ("Data report. MHT.FTL", Htmlfile2, Map, "Doc");} catch (IOException e) {e.printstacktrace ();} catch (Templateexce Ption e) {e.printstacktrace ();} return SUCCESS;  downloadaction for generated file downloads   package com.jr.cont; Import; Import; Import; Import; Import; Import Javax.servlet.http.HttpServletResponse; Import Org.apache.struts2.ServletActionContext; Import Com.opensymphony.xwork2.ActionSupport; /*** download Word's action*/public class Downloadaction extends Actionsupport {private staticFinal long serialversionuid = 8448176878783491691L; @Override public String Execute () throws Exception {HttpServletResponse resp = servletactioncontext.getresponse (); String path = Servletactioncontext.getservletcontext (). Getrealpath ("/"); String filename = "Data report. Mht.doc"; File name of the generated file this needs to be dynamically obtained outputstream out;//output stream inputstream in;//read local file input stream/get local input stream file = new file (path + file name); in = new FileInputStream (file); Sets the MIME type Resp.setcontenttype ("content-disposition;charset=gb2312") of the response body; Resp.setheader ("Content-disposition", "attachment" + "filename=" + New String (Filename.getbytes (), "iso-8859-1")); Send local file to client out = Resp.getoutputstream (); int byteread = 0; byte[] buffer = new BYTE[512]; while ((Byteread = (buffer))!=-1) {out.write (buffer, 0, byteread);} in.close (); Out.close (); return null; }}  struts.xml <! DOCTYPE struts Public "-//apache Software foundation//dtd struts Configuration 2.0//en" " Struts-2.0.dtd "> <struts> <package name= "tutorial" extends= "Struts-default" > <action name= "Export" class= " Com.jr.cont.ExportWordAction "> <result name=" Success ">/success.jsp</result> </action> < Action name= "Download" class= "com.jr.cont.DownloadAction" ></action> </package> </struts>   Effect: Download effect map: Source code I will package uploaded to my resources ... The above code does not carry on the Chinese processing, now complements, the downloading document does not know how to enter and to revise, package com.jr.cont; The/** encoding tool class encodes the Chinese to be placed in the Freemark/public class StringUtils {/** * converts the given STR to Unicode in the 10 notation, in the form of: Aunt is currently only for the MHT template transcoding * @param STR * @return */public static string Encode2htmlunicode (String str) {if (str = null) return ""; StringBuilder sb = new StringBuilder (Str.length () * 2); for (int i = 0; i < str.length (); i++) {Sb.append (Encode2htmlunicode (Str.charat (i))), return sb.tostring (); public static String Encode2htmlunicode (char character) {if (character > 255) {return "&#" + (character & 0 XFFFF) + ";"; else {return string.valueof (character);}} PubliC Static String Encode2htmlunicode (Character Character) {if (Character = = null) return null; return Encode2htmlunicode (Ch Aracter.charvalue ()); public static void Encode2htmlunicode (string[] Value {if (value = NULL | | Value.length < 1) return to (int i = 0 ; i < value.length; i++) {Value[i] = Encode2htmlunicode (Value[i]);} }  

The characters you want to encode in the file can be used as follows

Stringutils.encode2htmlunicode ("name");

Have no effect on English.

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: 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.