freemarker导出word案例
时间: 2023-09-02 17:11:42 浏览: 107
java Freemarker生成word
5星 · 资源好评率100%
好的,以下是一个使用freemarker导出Word文档的例子,供您参考:
1. 首先需要在pom.xml文件中引入以下依赖:
```
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
2. 编写一个freemarker模板,例如sample.ftl:
```
<html>
<head>
<title>${title}</title>
</head>
<body>
<h1>${title}</h1>
<table>
<#list data as item>
<tr>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.age}</td>
</tr>
</#list>
</table>
</body>
</html>
```
3. 编写Java代码:
```
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class WordExportDemo {
public static void main(String[] args) throws Exception {
//创建一个Freemarker模板解释器
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
//设置模板文件路径
cfg.setClassForTemplateLoading(WordExportDemo.class, "/");
cfg.setDefaultEncoding("UTF-8");
//获取模板文件
Template template = cfg.getTemplate("sample.ftl");
//构造数据
Map<String, Object> data = new HashMap<>();
data.put("title", "员工信息表");
List<Map<String, Object>> empList = new ArrayList<>();
empList.add(createEmp("001", "John", 25));
empList.add(createEmp("002", "Mike", 32));
empList.add(createEmp("003", "Lucy", 28));
data.put("data", empList);
//将数据写入到Word文档
XWPFDocument doc = new XWPFDocument();
XWPFParagraph para = doc.createParagraph();
XWPFRun run = para.createRun();
//将模板文件和数据合并,输出到流中
template.process(data, new OutputStreamWriter(run::addCarriageReturn));
//将文档输出到文件
File outputFile = new File("employee.docx");
FileOutputStream outputStream = new FileOutputStream(outputFile);
doc.write(outputStream);
outputStream.close();
}
private static Map<String, Object> createEmp(String id, String name, int age) {
Map<String, Object> emp = new HashMap<>();
emp.put("id", id);
emp.put("name", name);
emp.put("age", age);
return emp;
}
}
```
以上代码实现了将freemarker模板和数据合并,并将结果输出到Word文档中。在此例子中,我们使用了基于Apache POI的XWPFDocument类来创建Word文档。
阅读全文