导出问卷为word
一、获得问卷id
前端页面应该有保存,直接获取
二、通过id查询获得问卷数据(json)
selectById()
三、解析json,获得所需数据(title,question,answer)
四、新建模板,将数据传入模板并保存
准备word模板
此处的《》不是直接打双引号,需要用word的插入->文档部件->域
下载aspose-word.jar包
导入pom.xml文件
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>18.10</version>
<classifier>jdk16</classifier>
</dependency>
新建License.xml验证文件
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
新建验证授权方法
/**
* 判断是否有授权文件 如果没有则会认为是试用版,转换的文件会有水印
* @return
*/
public static boolean getLicense() {
boolean result = false;
try {
InputStream is = new FileInputStream("src/main/resources/License.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
对模板进行操作
public static void main(String[] args) throws Exception {
if (!getLicense()) {// 验证License 若不验证则生成的word文档会有水印产生
System.out.println("验证失败");
return;
}
//载入模板
Document doc = new Document("src/main/resources/wordTemplate/template.docx");
//提供数据源
String[] fieldNames = new String[] {"title", "surveyId", "question", "answer1", "answer2", "answer3", "answer4"};
Object[] fieldValues = new Object[] {"问卷调查模板生成", "999666", "请问生成成功了吗", "成功了", "失败了","差不多","无法知道"};**
//合并模版,相当于页面的渲染
doc.getMailMerge().execute(fieldNames, fieldValues);
//保存合并后的文档
doc.save("src/main/resources/wordTemplate/template1.docx");//本机测试约110ms
//还可以直接保存为pdf,不过所需时间大约为20倍
//doc.save("src/main/resources/wordTemplate/template1.pdf",SaveFormat.PDF);//本机测试约2200ms
}