java generate Word document recently need to do a export word function, search on the web, useful poi,jxl,itext such as jar generated a Word file and then write the data to the file, The API is very cumbersome and the style is not beautiful, so chose another way----feemarker based on Word template export, this method is very simple and the export style is beautiful, the principle is to do a Word template, the template variable data with ${xxx} This way to fill in, and then export only need to read the template and then replace the corresponding data with the ${xxx} can be . One, simple template export (without pictures, no table loop) 1, create a new Word document, enter the following class capacity: 2, Save the Word file as an XML format (note Save As, not directly to the extension) 3, change the XML file extension directly to FTL4, and complete the export with Java code (import Freemarker.jar required) package test; Import Java.io.bufferedwriter;import Java.io.file;import Java.io.fileoutputstream;import Java.io.outputstreamwriter;import Java.io.writer;import Java.util.hashmap;import Java.util.Map; import Freemarker.template.configuration;import Freemarker.template.template; public class Test {public static void Main (string[] args) throws Exception {Testexportsimpleword ();} public static void Testexportsimpleword () throws Exception {//data to be populated, note that the key to map is consistent with the XXX of ${xxx} in Word map<string , string> dataMap = new hashmap<string, string> ();d atamap.put ("WHB", "Wang Haibo" //configuration is used to read the FTL file configuration configuration = new configuration (); configuration.setdefaultencoding ("Utf-8"); /** the following are the two ways to specify the path to the directory where the FTL file is located, both of which are the path to the directory where the FTL file is specified, not the path of the FTL file *///the first way to specify the path (as specified by the relative path of a class)/ Configuration.setclassfortemplateloading (This.getclass (), ""); //the second way to specify the path, my path is c:/ A.ftlconfiguration.setdirectoryfortemplateloading (New file ("c:/")) //output document path and name file OutFile = new file ("c:/ Test.doc "); //reads the FTL file with utf-8 code t = configuration.gettemplate (" TEST.FTL "," utf-8 "); Writer out = new BufferedWriter (new OutputStreamWriter (New FileOutputStream (OutFile), "Utf-8"), 10240); T.process ( DataMap, out); Out.close ();}} 5, at this time in the D disk generated a Test.word, open can see ${xxx} has been replaced two, Word file import picture 1, create a Word document, insert a picture in the place of a random image 2, save Word as XML3, change the XML extension to FTL4, open the FTL file, search W:bindata or PNG to quickly position the image, the image has been encoded as a 0-z string, as follows: 5, The above 0-z string all deleted, write on ${IMGSTR} (variable name casually write) after saving 6, import the image of the code is the same as the above code, but also to create a map, the data stored in the map, but we want to encode the image in code, it is also compiled into 0-z string: Map<string,string> DataMap = new hashmap<string,string> ();d atamap.put ("Imgstr", Getimagestr ()); // .... Remainder omitted This is the code that encodes the picture: public String Getimagestr () {String imgfile = "D:/aa.png"; InputStream in = null;byte[] Data = null;try {in = new FileInputStream (imgfile);d ata = new byte[in.available ()];in.read (data); In.close ();} catch ( Exception e) {e.printstacktrace ();} Base64encoder encoder = new Base64encoder (); return Encoder.encode (data);} Note: The code needs to use the Sun.misc.BASE64Encoder class, which is the class in the JDK, but is not accessed by default in Eclipse, and needs to be set up: Right-click on the project-->build path--> Configure Build path... Double-click access Rules, click Add, select Accessible, enter * * below, OK, so you can access the Sun.misc.BASE64Encoder class. third, export the Loop table 1, create a new Word document, insert the following table: 2, Save as XML, change the extension to FTL3, search W:tr can find the beginning and end of the line (note that the first pair of W:TR is the table header, you should find the second pair W:TR),: 4, with < #list userlist as user> </#list > tags enclose the second pair of W:tr tags (userlist is the key of the collection, User is a collection of each element, similar to <c:foreach items= ' userlist ' var= ' user ' >),: 5, parsing the FTL file This is the user class Java code
- public class User {
- private string A;
- private string B;
- private string C;
- //Generate set and Get methods, omitted here
- }
This is the code that parses the FTL file, just like the above, except that the map value is a collection. public void Exportlistword () throws exception{//construction data map< string,list> DataMap = new hashmap<string,list> (); list<user> list = new arraylist<user> (); for (int i=0;i<10;i++) {User user = new User (); User.seta ("a" + (i+1) ); User.setb ("B" + (i+1)); User.setc ("C" + (i+1)); List.add (user); Datamap.put ("userlist", list), configuration configuration = new configuration (); Configuration.setdefaultencoding ("Utf-8"); Configuration.setdirectoryfortemplateloading (New File ("C:/")); File OutFile = new file ("D:/test.doc"); Template t = configuration.gettemplate ("C.FTL", "utf-8"); Writer out = new BufferedWriter (new OutputStreamWriter (New FileOutputStream (OutFile), "Utf-8"), 10240); T.process ( DataMap, out); Out.close ();} If you need an index of the output set, use ${user_index} to . four, FAQ solution 4.1, the exception information is as follows: XML code
- freemarker.core.ParseException:Encountered "<" at line 3, column 28888 in TEST.FTL.
- was expecting one of:
- <string_literal>&NBSP;..
- <raw_string>&NBSP;..
- "false" ...
- "true" ...
- <integer>&NBSP;..
- <decimal>&NBSP;..
- "." ...
- "+" ...
- "-" ...
- "!" ...
- "[" ...
- "(" ...
this is because in the writing ${xxx} expression, xxx and the preceding text style inconsistent, after the Save as XML you can search for "${", you will find such a situation: because ${xxx} In the XXX format is inconsistent with the text in front of it, then in the generation of XML, there will be some decorated with xxx-style tags, such as the modification of XXX fonts, colors and other labels, so in Word seems to write ${xxx} actually converted into XML after the ${<w:color ... >xxx</w:color>}, so that the tag in the El expression cannot parse the error, you can remove the ${} inside the label only leave xxx or delete "${" and "}" and then to XXX plus El expression can solve this problem . five, Javaweb in the use of response export (attention to coding problems, to prevent Chinese garbled) map<string,string> DataMap = new hashmap<string,string> (); Datamap.put ("username", "Zhang San");d atamap.put ("Sex", "male"); configuration configuration = new configuration (); Configuration.setdefaultencoding ("Utf-8"); Configuration.setdirectoryfortemplateloading (New File ( Request.getrealpath ("/") + "/templete"));//Specify the directory of FTL, according to their own change response.setcontenttype ("Application/msword"); Response.setheader ("Content-disposition", "attachment;filename=\" "+ New String (" file name. doc ". GetBytes (" GBK ")," Iso8859-1 ") +" \ ""); Response.setcharacterencoding ("Utf-8");//This sentence is very critical, otherwise the Word document is all garbled printwriter out = Response.getwriter (); Template T = configuration.gEttemplate ("TEST.FTL", "utf-8");//Read FTL file t.process (DataMap, out) with UTF-8 encoding; Out.close ();
Java uses Freemarker to generate Word documents