Recently, a project has to export word documents. I have been working hard for a long time. I found that it is more convenient and convenient to use freemarker templates. I will summarize the key steps for your reference. Here is a simple example of the test paper generation.
1. Production of templates
First use Word to make a template, as shown in the figure below:
(Note that there is a table above, I set the border invisible) Then save it as an XML file, and then use the tool to open the XML file. Someone uses firstobject XML Editor to feel that it is not as good as notepad++. I use notepad++ here, mainly because it has highlighting and automatically pairs with elements. The effect is as follows:
The black place above is basically the place we want to replace later. For example, if xytitle is replaced by ${xytitle}, you should pay great attention to the table. For example, the table below multiple-choice questions can be positioned by searching for multiple-choice questions. A pair of <w:tr></w:tr> represents a row, that is, a record (a question). Here we need to use a pair of <#list></#list> to include it in order to subsequently fill in the data. For details, please refer to the grammar of the Freemarker page. For example, here multiple-choice questions, we have two behaviors and one record, so we need <#list></#list> to include two rows, as shown in: <#list table1 as plan1><w:tr>Question number Question</w:tr><w:tr>Option</w:tr></#list>, and then find the corresponding xzn, xztest, ans1, ans2, ans3, and ans4 to replace it with ${plan1.xzn}, ${plan1.xztest}, ${plan1.ans1}, ${plan1.ans2}, ${plan1.ans3}, ${plan1.ans4}, note that table1 and plan1 are named here. Table1 and subsequent filling data should be used. Other replacements are the same, and the results are as follows:
After saving, modify the suffix name to ftl, and the template is completed.
2. Programming implementation
The freemarker-2.3.13.jar package is used here, and 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.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 data file of the modulo script //Set the modulo script device method and path, FreeMarker supports multiple template loading methods. You can re-servlet, classpath, and database loading. // Here our template is placed under the template package configuration.setClassForTemplateLoading(this.getClass(), "/template"); Template t=null; try { //test.ftl is the template 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"); //This place is indispensable for encoding streaming. When called separately using main(), it should be OK, but if it is a web request to export the word document will not be opened after exporting, and the package XML file is incorrect. The main reason is that the encoding format is incorrect and cannot be parsed. //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 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 UnsupportedEncodingException */ public static void main(String[] args) throws UnsupportedEncodingException {; Map<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put("xytitle", "Exam Paper"); int index = 1; // Multiple choice List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();// Question 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 allows multiple terminals to be connected to one host at the same time, and multiple users can use the computer interactively through their respective terminals at the same time. "); map.put("ans1", "A" + index); map.put("ans2", "B" + index); map.put("ans3", "C" + index); map.put("ans4", "D" + index); list1.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); dataMap.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 a ___ system software________ in the computer system, which manages and controls _________ in the computer system."); list2.add(map); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("fill", index + "."); map1.put("def", "Intermediate Scheduling" + index); list12.add(map1); index++; } dataMap.put("table2", list2); dataMap.put("table12", list12); // Judgment question List<Map<String, Object>> list3 = new ArrayList<Map<String, Object>>(); List<Map<String, Object>> list13 = new ArrayList<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", "Composite firewall Firewall is the isolation point between the internal network and the external network, and plays the role of monitoring and isolating the communication flow of the application layer, and is also often combined with the function of filters. "); list3.add(map); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("judge", index + "."); map1.put("hij", "v" + index); list13.add(map1); index++; } dataMap.put("table3", list3); dataMap.put("table13", list13); // Short answer question 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", "Describe the difference between job scheduling, intermediate scheduling and process scheduling, and analyze which level of scheduler should be responsible for the following problems."); list4.add(map); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("answer", index + "."); map1.put("xyz", "Describe the difference between job scheduling, intermediate scheduling and process scheduling, and analyze which level of scheduler should be responsible for the following problems."); list14.add(map1); index++; } dataMap.put("table4", list4); dataMap.put("table14", list14); MDoc mdoc = new MDoc(); mdoc.createDoc(dataMap, "E:/outFile.doc"); } } Note that the key in the map above must correspond to the template, otherwise an error will be reported. The effects are as follows:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.