*** 所有目录参数皆为项目相对路径
一、基础准备
1.1 Maven构建项目
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.12</version>
</dependency>
1.2 获取资源绝对路径
public static String getRealPath(String dirPath) {
//利用资源加载器获取资源URL
String path = Class.class.getResource("/").getPath();
return path + dirPath;
}
1.3 获取目录下所有文件
/**
* 获取目录下所有文件(默认不存在目录下同时存在文件和文件夹)
*
* @param targetPath
* @return
*/
public static List<File> getFiles(String targetPath) {
String realPath = getRealPath(targetPath);
List<File> list = new ArrayList<>();
if (StringUtils.isBlank(realPath)) {
return null;
}
File file = new File(realPath);
if (file.isFile()) {
list.add(file);
return list;
} else {
File[] files = file.listFiles();
return files == null ? null : Arrays.asList(files);
}
}
1.4 创建FTL模版
1.5 获取填充数据
/**
* 注意dataMap里存放的数据Key值要与模板中的参数相对应
*
* @param target
*/
private static Map<String, Object> getData(Object target) {
Map<String, Object> map = new HashMap<>();
Class<?> beanClass = target.getClass();
Field[] declaredFields = beanClass.getDeclaredFields();
for (Field field : declaredFields) {
fi