需求说明
根据已有问题选项数据生成一个调查问卷word文档
提示:以下是本篇文章正文内容
一、技术选型
提示:由于poi-tl依赖apache-poi版本,现有框架中包含的apache-poi版本为4.1.2,所以这里未选用最新版本的poi-tl
二、maven依赖
代码如下(示例):
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.4</version>
</dependency>
三、poi-tl模板
{{?questions}}
{{no}}. {{question}}
{{?answers}}
{{answer}}
{{/answers}}
{{/questions}}
四、java代码
public static void main(String[] args) {
// 测试,采用当前桌面路径
File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
String desktopPath = desktopDir.getAbsolutePath() + File.separator;
// poi-tl模板文件
File templateFile = new File(desktopPath + "template.docx");
// 生成文件
File targetFile = new File(desktopPath + "target.docx");
// 问题数据结构
Map<String, Object> questionsMap = new HashMap<>();
List<Map<String, Object>> questionsListMap = new ArrayList<>();
Map<String, Object> question1Map = new HashMap<>();
Map<String, Object> question2Map = new HashMap<>();
// 构建数据,key值保持和模板一致
// 问题1:
question1Map.put("no","1");
question1Map.put("question","先有鸡还是先有蛋?");
question1Map.put("answers", new ArrayList<Map<String, Object>>() {
{
add(new HashMap<String, Object>(){
{
put("answer","A.鸡");
}
});
add(new HashMap<String, Object>(){
{
put("answer","B.蛋");
}
});
}
});
questionsListMap.add(question1Map);
// 问题2:
question2Map.put("no","2");
question2Map.put("question","人最多有几颗智齿?");
question2Map.put("answers",new ArrayList<Map<String, Object>>() {
{
add(new HashMap<String, Object>(){
{
put("answer","A.两颗");
}
});
add(new HashMap<String, Object>(){
{
put("answer","B.四颗");
}
});
}
});
questionsListMap.add(question2Map);
questionsMap.put("questions", questionsListMap);
// 调用poi-tl方法生成文档
XWPFTemplate template = XWPFTemplate.compile(templateFile).render(questionsMap);
try {
template.writeAndClose(new FileOutputStream(targetFile));
} catch (IOException e) {
e.printStackTrace();
}
}
官网也提供了很多数据模型,大家可以自行选择使用,这里仅做简单示例
五、结果
总结
重点是poi-tl的模板使用方式,参考官网提供的示例即可实现。
构造数据时可采用官网提供的多种方式,也可采用SpringEL表达式构造