Home Java javaTutorial Practical example of using freemarker to export word using Java

Practical example of using freemarker to export word using Java

Jan 05, 2017 pm 01:18 PM

A recent project required exporting a word document. After struggling for a long time, I found that it was more convenient and trouble-free to use the freemarker template. Now I will summarize the key steps for your reference. Here is a simple example of test paper generation.

1. Template production

First use Word to make a template, as shown below:

Practical example of using freemarker to export word using Java

(Note that there are tables above , I set the border to be invisible) and then save it as an XML file. Then use a tool to open the xml file. Some people use firstobject XML Editor and feel that it is not as good as notepad++. I use notepad++ here, mainly for highlighting and automatic pairing with elements. The effect As follows:

Practical example of using freemarker to export word using Java

The black area above is basically the place we will replace later, such as replacing xytitle with ${xytitle}. Pay special attention to the table, such as below the multiple-choice question We can locate the table through search. A pair of represents a row, that is, a record (a question). Here we use a pair of < ;#list>#list> to include it for subsequent filling of data. For details, please refer to the Freemarker page syntax. For example, for the multiple-choice question here, we have two lines for one record, so we need # list> should include two lines, in the form: Question number Options, and then find the corresponding xzn, xztest, ans1, ans2, ans3, ans4 and replace them with ${plan1.xzn}, ${plan1.xztest}, ${plan1.ans1}, ${plan1 .ans2}, ${plan1.ans3}, ${plan1.ans4}, pay attention to the naming of table1 and plan1 here, which will be used for subsequent filling of table1 data. The same operation is performed for other replacements, and the result is as follows:

Practical example of using freemarker to export word using Java

After saving, change the suffix to ftl, and the template is now complete.

2. Programming implementation

The freemarker-2.3.13.jar package is used here, 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.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 要填入模本的数据文件
  //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
  //这里我们的模板是放在template包下面
  configuration.setClassForTemplateLoading(this.getClass(), "/template");
  Template t=null;
  try {
   //test.ftl为要装载的模板
   t = configuration.getTemplate("fctestpaper.ftl");
  } catch (IOException e) {
   e.printStackTrace();
  }
  //输出文档路径及名称
  File outFile = new File(fileName);
  Writer out = null;
  FileOutputStream fos=null;
  try {
   fos = new FileOutputStream(outFile);
   OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
   //这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
   //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("---------------------------");
 }
}
Copy after login

Then just 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", "试卷");
  int index = 1;
  // 选择题
  List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();//题目
  List<Map<String, Object>> list11 = new ArrayList<Map<String, Object>>();//答案
  index = 1;
  for (int i = 0; i < 5; i++) {
  
   Map<String, Object> map = new HashMap<String, Object>();
   map.put("xzn", index + ".");
   map.put("xztest",
     "( )操作系统允许在一台主机上同时连接多台终端,多个用户可以通过各自的终端同时交互地使用计算机。");
   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);
  
  // 填空题
  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",
     "操作系统是计算机系统中的一个___系统软件_______,它管理和控制计算机系统中的___资源_________.");
   list2.add(map);
  
   Map<String, Object> map1 = new HashMap<String, Object>();
   map1.put("fill", index + ".");
   map1.put("def", "中级调度" + index);
   list12.add(map1);
  
   index++;
  }
  dataMap.put("table2", list2);
  dataMap.put("table12", list12);
  
  // 判断题
  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",
     "复合型防火墙防火墙是内部网与外部网的隔离点,起着监视和隔绝应用层通信流的作用,同时也常结合过滤器的功能。");
   list3.add(map);
  
   Map<String, Object> map1 = new HashMap<String, Object>();
   map1.put("judge", index + ".");
   map1.put("hij", "对" + index);
   list13.add(map1);
  
   index++;
  }
  dataMap.put("table3", list3);
  dataMap.put("table13", list13);
  
  // 简答题
  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", "说明作业调度,中级调度和进程调度的区别,并分析下述问题应由哪一级调度程序负责。");
   list4.add(map);
  
   Map<String, Object> map1 = new HashMap<String, Object>();
   map1.put("answer", index + ".");
   map1.put("xyz", "说明作业调度,中级调度和进程调度的区别,并分析下述问题应由哪一级调度程序负责。");
   list14.add(map1);
  
   index++;
  }
  dataMap.put("table4", list4);
  dataMap.put("table14", list14);
  
  MDoc mdoc = new MDoc();
  mdoc.createDoc(dataMap, "E:/outFile.doc");
 }
  
}
Copy after login

Note that the key in the map above must correspond to the key in the template, otherwise an error will be reported. The effect is as follows:

Practical example of using freemarker to export word using Java

The above is the entire content of this article. I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.

For more practical examples of Java using freemarker to export word, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles