Java Export Word Document

Source: Internet
Author: User


Use the Freemarker template to export Word documents with more. It is also used in this way.

1 edit a Word file template, used in the program need to read into the data filled in the template is replaced by letters, note that Word version is word2003 or higher than this version;

such as: Test.doc


2 Save the template as an XML file;

such as: Test.xml



3 in the XML to find before the value of the letter replaced with ${}, such as ${test} ${guojia}, the file name is changed to TEST.FTL;

4 Create a new folder under the WebContent directory of the project and put the Test.xml in.

    5 writing code;

Package Com.web.action;import Java.io.file;import Java.io.fileinputstream;import java.io.fileoutputstream;import Java.io.inputstream;import Java.io.outputstream;import Java.io.outputstreamwriter;import Java.io.Writer;import Java.util.hashmap;import Java.util.map;import Javax.servlet.servletcontext;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.struts2.servletactioncontext;import Org.springframework.stereotype.controller;import Com.opensymphony.xwork2.actionsupport;import Freemarker.template.configuration;import Freemarker.template.defaultobjectwrapper;import freemarker.template.Template; @Controllerpublic class Exportaction  Extends Actionsupport{//word template public static final String word_template= "/TEST.FTL"; The directory where the template is stored public static final string template_path= "/template";//temporary file public static final string word_temp= "/temp.doc"; Public String Executeexport () {httpservletrequest request=servletactioncontext.getrequest (); HttpservletresPonse response=servletactioncontext.getresponse (); try {Map datamap=new HashMap (); if (GetData (Request, Response, DATAMAP) {file Previewfile=new file (Request.getsession (). Getservletcontext (). Getrealpath (Word_temp)); InputStream Is=new FileInputStream (previewfile); Response.reset (); Response.setcontenttype ("application/vnd.ms-word;charset= UTF-8 "), Response.setheader (" Content-disposition "," attachment; Filename=export.doc "); OutputStream os= Response.getoutputstream (); byte[] B=new byte[1024];int len;while ((Len=is.read (b))!=-1) {os.write (b, 0, Len);} Is.close (); Os.flush (); Os.close ();}} catch (Exception e) {e.printstacktrace ();} return null;} public static Template configtemplate (HttpServletRequest request,string temp) {Template Template=null;try { Configuration cfg=new configuration (); ServletContext application=request.getsession (). Getservletcontext (); System.out.println (Application.getrealpath (Template_path)); Cfg.setdirectoryfortemplateloading (New Java.io.File ( Application.getrealpath (Template_path))); CFG. Setobjectwrapper (New Defaultobjectwrapper ()); Template=cfg.gettemplate (temp, "utf-8");} catch (Exception e) {e.printstacktrace ();} return template;} public static void Topreview (HttpServletRequest request,string temp,map<?,? > Root) {try {String previewpath= Request.getsession (). Getservletcontext (). Getrealpath ("") +word_temp; Template tmplate=configtemplate (Request, temp); FileOutputStream fis=new FileOutputStream (Previewpath); Writer out=new outputstreamwriter (FIS, "utf-8"); tmplate.process (root, out); Out.flush (); Out.close ();} catch (Exception e) {e.printstacktrace ();}} public boolean getData (HttpServletRequest request,httpservletresponse response,map dataMap) {datamap.put ("test", "testing" );d atamap.put ("Guojia", "China");d atamap.put ("Shoudu", "capital"), Topreview (Request, word_template, DATAMAP); return true;}}


6 I used the Struts2,executeexport as the method to process the request, before the return value I write an arbitrary string, do not affect the result but throw an exception java.lang.IllegalStateException, I changed the returned string to NULL, This exception has been resolved. Oh of course this is unrelated to the export of things, just in this program encountered this problem.

7 Export Results:



















































































Java Export Word Document

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.