Java Web generates Word document (freemarker mode)

Posted by ptbsG_Man on Fri, 06 Dec 2019 09:36:59 +0100

First, add the following dependency to the pom file (if not the Maven project, just import the jar package into the project)

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.23</version>
</dependency>

1. Create a word document with format, and replace the data to be displayed dynamically with variable character. As follows:

2. Save the document created by 1 as. xml format.

3. Edit the. xml file of the above 2 to remove redundant xml tags, as shown in the following figure (the red circle is the correct format, which should be wrapped by ${variable character})

4. Save the above 3 documents in. ftl format and copy them to the Web project (table of contents below).

The 5.JSP page provides buttons for generating word documents.

<a href="javascript:;" onclick="exportWord('${rightId}')" class="btn btn-success radius"><i class="Hui-iconfont">&#Xe644; < / I > export word</a> 

JS Code:
//Generate word document
function exportWord(rightId){
    layer.confirm('Confirm to build word Documents?',function(index){
        //close window
        layer.close(index);
        window.location.href ="<%= basePath%>/biz/SysRight_exportWord.action?rightId="+rightId+""
	});
}

The effect is as follows:

 

6. The exportWord() method in action.

/**
	 * Generate word document (for test use)
	 * @Description: TODO
	 * @param @return
	 * @param @throws Exception   
	 * @return String  
	 * @throws
	 * @author uug
	 * @date 2018 December 9th 2013
	 */
	public String exportWord() throws Exception {
        //Data to be displayed
		sysRight = sysRightService.exportWord(sysRight.getRightId());
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		//Create Map
        Map<String, Object> map = new HashMap<String, Object>();
        //put the data into the Map, the first parameter is the corresponding ${} name in the. ftl file, and the second parameter is the content to be displayed
        map.put("rightId",sysRight.getRightId());
        map.put("rightName",sysRight.getRightName());
        map.put("resourcePath",sysRight.getResourcePath());
        map.put("rightPid",sysRight.getRightPid());
        //Template name to call
        String downloadType = "test";
        //Name on export
        String fileName = "Permission list";
        WordUtils.exportMillCertificateWord(request,response,map,downloadType , fileName);
		return null;
	}

6.WordUtils tool class.

@SuppressWarnings("deprecation")
public class WordUtils {
	//configuration information
    private static Configuration configuration = null;
  //Note that the location of template files is dynamically obtained by using WordUtils' classloader
    private static final String templateFolder = WordUtils.class.getClassLoader().getResource("../../").getPath() + "WEB-INF/asserts/templete/";
    //Used to store all. ftl files
    private static Map<String, Template> allTemplates = null;
	
	static {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		allTemplates = new HashMap<String, Template>();
		try {
			configuration.setDirectoryForTemplateLoading(new File(templateFolder));
			//Save test.ftl file to Map
			allTemplates.put("test", configuration.getTemplate("test.ftl"));
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	private WordUtils() {  
        throw new AssertionError();  
    }
 
	/**
	 * 
	 * @Description: TODO
	 * @param @param request
	 * @param @param response
	 * @param @param map Data written to file
	 * @param @param downloadType  You need to call the. ftl file corresponding to Map allTemplates
	 * @param @param fileName0  Set the browser to process the filename as a download
	 * @param @throws IOException   
	 * @return void  
	 * @throws
	 * @author uug
	 * @date 2018 December 9th 2013
	 */
    public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map, String downloadType, String fileName0) throws IOException {
        //Define the Template object. Note that the Template type name should be consistent with the downloadType
    	Template template= allTemplates.get(downloadType);
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // Call the createDoc method of the tool class to generate a Word document
            file = createDoc(map,template);
            fin = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // Set the browser to process the filename as a download
            String fileName = fileName0 + ".doc";
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
 
            out = response.getOutputStream();
            byte[] buffer = new byte[512];  // Buffer
            int bytesToRead = -1;
            // Output the contents of the read Word file to the 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
        }
    }
 
    /**
     * Create doc document
     * @Description: TODO
     * @param @param dataMap
     * @param @param template
     * @param @return   
     * @return File  
     * @throws
     * @author uug
     * @date 2018 December 9th 2013
     */
    private static File createDoc(Map<?, ?> dataMap, Template template) {
        String name = "temp" + (int) (Math.random() * 100000) + ".doc"; 
        File f = new File(name);
        Template t = template;
        try {
            // FileWriter cannot be used in this place because the encoding type needs to be specified, otherwise the generated Word document cannot be opened because of an unrecognized encoding
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }
}

7. The effect is as follows:

Topics: xml FreeMarker encoding Maven