前言 最近做了一个调查问卷导出的功能,需求是将维护的题目,答案,导出成word,参考了几种方案之后,选择功能强大的freemarker+固定格式之后的wordxml实现导出功能。导出word的代码是可
前言
实现过程概览
详细的实现过程
准备好word的样式
样式没有问题后,我们选择另存为word xml 2003版本。将会
生成一个xml
文件。
格式化xml,并用freemarker语法替换xml
像右侧的调查问卷这个就是个
标题,我们实际渲染的时候应该将其进行替换,比如我们的程序数据map中,有title
属性,我们想要这里展示,我们就使用语法${title}即可。
freemarker的具体语法,可以参考freemarker的问题,在这里我给出几个简单的例子。
比如我们将所有的数据放置在dataList中,所以我们需要判断,dataList是不是空,是空,我们不应该进行下面的逻辑,不是空,我们应该先循环题目是必须的,答案是需要根据类型进行再次循环的。语法参考文档,这里不再赘述。
程序端引入freemarker
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
public class WordUtils {
private static Configuration configuration = null;
private static final String templateFolder = WordUtils.class.getClassLoader().getResource("").getPath()+"/templates/word";
static {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
try {
configuration.setDirectoryForTemplateLoading(new File(templateFolder));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @Description:导出word,传入request,response,map就是值,title是导出问卷名,ftl是你要使用的模板名
*/
public static void exportWord(HttpServletRequest request,HttpServletResponse response,Map map,String title,String ftlFile) throws Exception {
Template freemarkerTemplate = configuration.getTemplate(ftlFile);
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
file = createDocFile(map,freemarkerTemplate);
fin = new FileInputStream(file);
String fileName = title + ".doc";
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
response.setHeader("Content-Disposition","attachment;filename="
+fileName);
out = response.getOutputStream();
byte[] buffer = new byte[512];
int bytesToRead = -1;
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer,bytesToRead);
}
}finally {
if(fin != null) fin.close();
if(out != null) out.close();
if(file != null) file.delete();
}
}
/**
* @Description:创建doc文件
*/
private static File createDocFile(Map<?,?> dataMap,Template template) {
File file = new File("init.doc");
try {
Writer writer = new OutputStreamWriter(new FileOutputStream(file),"utf-8");
template.process(dataMap,writer);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
}
WordUtils.exportWord(request,response,dataMap,"word","demo.ftl");
结语
总结