在一些项目中,会遇到导出固定格式的word文档,这个时候我们可以使用模板freemarker来实现,本文先分享简单的字符串填充。
比如现在有一个word模板的样式如下
我们填充好内容后(重点坑点:先采用记事本类似的将${A1}编辑好,复制到word模板中,确保${A1}是一个完整的整体);然后点击word,另存为word 2003 xml文档(.xml)。业务代码中我们生成数据,最后在检查结果一列使用${xxx}来获取数据。
private static void test001() throws Exception{
String word_xml_temp_01="D:\\data\\exportWord1\\tmp201.xml";
Map<String,String> resultMap=getData01();
String currentTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
String filePath = new StringBuilder(currentTime).append(".doc").toString();
FileUtil.mkdir(wordDir);
File outFile = new File(new StringBuilder(wordDir).append("/").append(filePath).toString());
Configuration configuration = new Configuration(Configuration.VERSION_2_3_20);
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File(wordDir));
InputStream inputStream = new FileInputStream(new File(word_xml_temp_01));
String fileXmlPath = new StringBuilder(currentTime).append(".xml").toString();
File xmlFile = new File(new StringBuilder(wordDir).append("/").append(fileXmlPath).toString());
FileUtils.copyInputStreamToFile(inputStream, xmlFile);
Template t = configuration.getTemplate(fileXmlPath, "utf-8");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 102400);
t.process(resultMap, out);
out.flush();
out.close();
}
private static Map<String, String> getData01() {
Map<String,String> resultMap=new HashMap<>();
resultMap.put("A1","A1-101");
resultMap.put("B1","B1-101");
resultMap.put("B2","B2-101");
resultMap.put("B3","B3-101");
resultMap.put("B4","B4-101");
resultMap.put("B5","B5-101");
resultMap.put("B6","B6-101");
resultMap.put("B7","B7-101");
return resultMap;
}
这样就在wordDir下面生成一份word文档,如果需要下载使用http中response输出即可;可以参考一下代码:
@RequestMapping(value = "/xxxx")
public void exportToWordById(HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, String> resultMap = getDataMap();//获取数据
String currentTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
String filePath = new StringBuilder(currentTime).append(".doc").toString();
FileUtil.mkdir(wordDir);
File outFile = new File(new StringBuilder(wordDir).append("/").append(filePath).toString());
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File(wordDir));
ClassPathResource classPathResource = new ClassPathResource(XMLPATH_XML);
InputStream inputStream = classPathResource.getInputStream();
String fileXmlPath = new StringBuilder(String.valueOf(currentTime)).append(".xml").toString();
File xmlFile = new File(new StringBuilder(wordDir).append("/").append(fileXmlPath).toString());
FileUtils.copyInputStreamToFile(inputStream, xmlFile);
Template t = configuration.getTemplate(fileXmlPath, "utf-8");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 102400);
t.process(resultMap, out);
out.flush();
out.close();
response.setContentType("application/msword");
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
String exportFileName = filePath;
String userAgent = request.getHeader("USER-AGENT");
if (StringUtils.isNotEmpty(userAgent)) {
if (userAgent.contains("MSIE")) {// IE浏览器
exportFileName = URLEncoder.encode(exportFileName, "UTF8");
} else if (userAgent.contains("Mozilla")) {// google,火狐浏览器
exportFileName = new String(exportFileName.getBytes(), "ISO8859-1");
} else {
exportFileName = URLEncoder.encode(exportFileName, "UTF8");// 其他浏览器
}
}
response.setHeader("content-disposition", "attachment;filename=" + exportFileName);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(outFile));
OutputStream os = response.getOutputStream();
byte[] bs = new byte[1024 * 10];
int size = bis.read(bs);
while (size > 0) {
os.write(bs, 0, size);
size = bis.read(bs);
}
bis.close();
os.flush();
if (outFile != null) {
outFile.delete();
}
if (inputStream != null) {
inputStream.close();
}
if (xmlFile != null) {
xmlFile.delete();
}
}
ClassPathResource classPathResource = new ClassPathResource(XMLPATH_XML);模板文件放置在maven项目源码的src\main\resources目录下;
重点:xml文件中${xxx}必须是一个整体;取值的key必须存在,可以设置初始化为空字符串;docker环境下读取路径使用ClassPathResource来读取模板文件。