打包过运行时后访问包所在目录文件
有这样一种场景,在我们使用word模板导出word时,需要加载模板,但是deepoove.poi模板解析只能解析绝对路径,发布时应该加上该模板的路径。
那么这样的写法对后期维护极度不友好,所以应该免配置,写法如下:
ApplicationHome ah = new ApplicationHome(getClass());
File file = ah.getSource();
仅仅两行代码,就能拿到我们当前运行的jar文件,然后获取jar包的父级目录的目标文件
file.getParentFile().getPath()+"/templates/qualityTemplate.docx"
以下是我用deepoove.poi导出word示例,希望对你有帮助
XWPFTemplate template = XWPFTemplate.compile(file.getParentFile().getPath()+"/templates/qualityTemplate.docx", config).render(
data
);
String fileName = "巡检记录.docx";
String filename = new String(fileName.getBytes("utf-8"));
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8");
response.addHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(filename,"UTF-8"));
ServletOutputStream out = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(out);
template.write(bos);
bos.flush();
out.flush();
PoitlIOUtils.closeQuietlyMulti(template, bos, out); //关闭流
其中data为我们需要的数据,为map类型