Generate document in Java-web (i)

Source: Internet
Author: User

There are a number of Java-based solutions, including the use of Jacob, Apache POI, Java2word, Itext, and so on, in fact, starting with Office 2003, you can convert Office documents to XML files so that only the content that needs to be filled in ${} placeholder, you can use a template engine like Freemarker to replace placeholders with real data, which is simpler than other scenarios.

For a practical example of a project, edit a word block first

1: Save the document in XML format:

2: After the save is recommended to use EditPlus, notepad++, sublime and other tools to open the view, because sometimes you write a placeholder may be opened, so that the freemarker can not be processed. The process is as follows:

3: Then save As. FTL format (choose to support all formats), well the non-code part is complete, start building your own project, I use the server is Tomcat 7.0.52,myelcipse2014; If eclipse needs to configure Web. XML to support Servlet3 annotations, you need to add the Freemarker jar file to your project before you build the project, you can get the latest version of Freemarker with the link below:/http Freemarker.org/freemarkerdownload.html

I'm building a maven project to get into the configuration files needed to find the Pom file Http://mvnrepository.com/artifact/org.freemarker/freemarker

4. Complete the JSP page code, to understand that name must be named in the FTL file corresponding to the value, so that the value can be taken. Uploading JSP Code

<%@ page language= "Java"Import= "java.util.*" pageencoding= "UTF-8"%><%String Path=Request.getcontextpath (); String BasePath= Request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%><% @taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>; } . textField {border:none; border-bottom:1px solid Gray; text-Align:center;} #file {border:1px solid black; width:80%; margin:0Auto;} H1 input{Font-size:72px;} TD TextArea {font-size:14px;} . key {width:125px; font-size:20px;} </style> <meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/><title> payment notice </title>class= "key" > Fee expiry time </td> <td height= "colspan=" 3 "><input type=" text "Name=" Ecendtimecost "class= "TextField" value= "${param.ecendtimecost}" style= "border:0px"/><span style= "Text-align:right" > Day </ span></td> </tr> <tr> &LT;TDclass= "Key" > Name </td> <td width= "212" ><input type= "text" Name= "uname"class= "TextField" value= "${param.uname}" style= "border:0px"/></td> <td width= "80"class= "Key" > Room number:</td> <td width= "355" > <input type= "text" name= "rooms" va                  Lue= "${param.room}" style= "border:0px"/> </td> </tr> <tr> <tdclass= "Key" > Electricity:</td> <td><input type= "text" Name= "Ecelectricityfee"class= "TextField" style= "border:0px" value= "${param.ecelectricityfee}"/> Yuan </td> <tdclass= "key" > Water:</td> <td><input type= "text" Name= "Ecwaterfee"class= "TextField" style= "border:0px" value= "${param.ecwaterfee}"/> Meta </td> </tr> <tr > &LT;TDclass= "Key" > Property management fee:</td> <td><input type= "text" Name= "Ecpropertyfee"class= "TextField" style= "border:0px" value= "${param.ecpropertyfee}"/> Yuan </td> <tdclass= "Key" > Parking fee:</td> <td><input type= "text" Name= "Ecparkingfee"class= "TextField" style= "border:0px" value= "${param.ecparkingfee}"/> Meta </td> </tr> <t r> <td height= "colspan=" 4 "class= "Key" >Total Amount:<input name= "text" style= "border:0px; width:5px "/> million <input name=" text "style=" border:0px; width:5px "/> Thousand <input name=" text "style=" border:0px; width:5px "/> Bai <input name=" text "style=" border:0px; width:5px "/> Pick <input name=" text "style=" border:0px; width:5px "/> Yuan <input style=" border:0px; width:5px "/> Angle <input name=" text "style=" border:0px;  width:5px "/> &nbsp;&nbsp; lowercase: <input name=" ecassessment "style=" border:0px; "Value=" ${param.ecassessment} "/>Yuan</td> </tr> </table> <p > Friendly reminder: 1, please owners in <input name= "Ecfeesdeadline"  Style= "border:0px; "Value=" ${param.ecfeesdeadline} "/> A few days ago to the community property Services, if there is any inconvenience can inform the property home-site charges,</p> <p > Property Services Hotline: 027-86889888, Those who do not pay more than the specified month will be subject to the relevant provisions for late fees. </p> <p>2, if it is found that there are errors on the notice, can be checked by the Property Services Office, the amount of the computer charges will prevail. </p> </br> <p style= "position:relative left:600px" > <input name= "text" style= "Bo rder:0px; Width:25px "/> Year <input name=" text "style=" border:0px; width:25px "/> Month <input name=" text "style=" border:0px; width:25px "/> Day </p> </div> <div align=" center "style=" MARGIN-TOP:15PX; " > <input type= "Submit" value= "Save Word Document"/> </div> </form> </body>

(Note that the El expression object cannot be used to param the Word document, so that the value of name is consistent.)

I'm giving a copy of the controller code in the SPRING-MVC, and if you can write it with a servlet, but it's necessary to support webservice annotations, you need to write the config file in the Web. XML container (servlet3.0).

If not supported on the trouble, so I use SPRINGMVC's core controller to write, not much to say to the code

 PackageCom.controller.zy;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.util.Enumeration;ImportJava.util.HashMap;ImportJava.util.Map;Importjavax.servlet.ServletException;ImportJavax.servlet.ServletOutputStream;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;Importcom.lovo.util.WordGenerator; @Controller Public classMyservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; @RequestMapping ("/savedocservlet.s")    protected voidService (HttpServletRequest req, HttpServletResponse resp)throwsservletexception, IOException {req.setcharacterencoding ("Utf-8"); Map<string, object> map =NewHashmap<string, object>(); Enumeration<String> Paramnames =Req.getparameternames (); //put form parameters into a key-value pair map by looping         while(Paramnames.hasmoreelements ()) {String key=paramnames.nextelement (); String value=Req.getparameter (key);          Map.put (key, value); }                //Tip: You should check that all fields are complete before invoking the tool class to generate a Word document//otherwise freemarker template attentive in processing may be unable to find the value of the error here temporarily ignore this stepFile File =NULL; InputStream Fin=NULL; Servletoutputstream out=NULL; Try {              //Call the tool class Wordgenerator Createdoc method to generate a Word documentFILE = Wordgenerator.createdoc (map, "Zhy")); Fin=Newfileinputstream (file); Resp.setcharacterencoding ("Utf-8"); Resp.setcontenttype ("Application/msword"); //set the browser to download the way the file is processed by default named Zhy.docResp.addheader ("Content-disposition", "Attachment;filename=zhy.doc"); out=Resp.getoutputstream (); byte[] buffer =New byte[512];//buffers            intBytestoread =-1; //output the contents of a read-in Word file to a browser by looping             while((Bytestoread = fin.read (buffer))! =-1) {out.write (buffer,0, Bytestoread); }          } finally {              if(Fin! =NULL) Fin.close (); if(Out! =NULL) Out.close (); if(File! =NULL) File.delete ();//Delete temporary files        }      }  }

5, also have a tool class as the middle call method use, do not think much, the code is fixed, take the file name can be

 PackageCom.lovo.util;ImportJava.io.File; ImportJava.io.FileOutputStream; Importjava.io.IOException; ImportJava.io.OutputStreamWriter; ImportJava.io.Writer; ImportJava.util.HashMap; ImportJava.util.Map; Importfreemarker.template.Configuration; Importfreemarker.template.Template;  Public classWordgenerator {Private StaticConfiguration Configuration =NULL; Private Staticmap<string, template> alltemplates =NULL; Static{Configuration=NewConfiguration (); Configuration.setdefaultencoding ("Utf-8"); Configuration.setclassfortemplateloading (wordgenerator.class, "/COM/LOVO/FTL"); Alltemplates=NewHashmap<> ();//Java 7 Diamond Syntax        Try{alltemplates.put ("Zhy", Configuration.gettemplate ("ZHY.FTL")); } Catch(IOException e) {e.printstacktrace (); Throw NewRuntimeException (e); }      }        PrivateWordgenerator () {Throw NewAssertionerror (); }         Public StaticFile Createdoc (map<?,? >dataMap, String type) {String name= "Temp" + (int) (Math.random () * 100000) + ". Doc"; File F=NewFile (name); Template T=alltemplates.get (type); Try {              //This place cannot be used filewriter because you need to specify an encoding type, the resulting Word document cannot be opened because of an unrecognized encodingWriter W =NewOutputStreamWriter (NewFileOutputStream (f), "Utf-8");              T.process (DataMap, W);          W.close (); } Catch(Exception ex) {ex.printstacktrace (); Throw NewRuntimeException (ex); }          returnF; }    }  

The code has been completed here, the deployment to the server can be used, hoping to help you.

Generate document in Java-web (i)

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.