#使用POI实现word模板导出
笔者的word模板没有存在的OSS中,因为模板不多,故我是在Spring boot项目中的resources中创建了一个专门用于存放word模板的文件夹
首先创建一个word模板
通过ctrl+F9编辑域空间 格式为${name}
InputStream in = null;
FileOutputStream out =null;
String filename ="";
/*
wordTemplate/ 是resources下创建的模板文件夹
*/
//读取模板
ClassPathResource classPathResource = new ClassPathResource("wordTemplate/" + "分析模板.docx");
String path = classPathResource.getPath();
in = this.getClass().getClassLoader().getResourceAsStream(path);
//获取context
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Freemarker);
IContext context = report.createContext();
FieldsMetadata fm = report.createFieldsMetadata();
//获取图片
fm.addFieldAsImage("one");
//这里我是获取的阿里OSS的线上图片
//不想使用线上的可以直接获取到路径上的图片即可
InputStream one= Downimage.steamToFile(lineImgUrl);
context.put("one",one);
//获取列表
fm.load("line",ImpactAnalysis.class,true);
List<ImpactAnalysis> analysisList = new ArrayList<>();
if (null!=mapNewLineRoad){
String repeatLine = mapNewLineRoad.getRepeatLine();
if(null!=repeatLine){
String[] split = repeatLine.split(";");
for (int i = 0; i < split.length; i++) {
ImpactAnalysis analysis = new ImpactAnalysis();
analysis.setAffectedLine(split[i]);
analysisList.add(analysis);
}
}
}
context.put("line",analysisList);
//这部分代码既是生成到当前项目的上一级工作空间
//这里是获取到当前项目的根
String property = System.getProperty("user.dir");
//当前项目根的上一级
property = property.substring(0, property.lastIndexOf(File.separator));
log.info("获取当前项目的相对路径,改路径为",property);
filename =property+"/新增路线分析表"+format+".docx";
out = new FileOutputStream(new File(filename));
report.process(context, out);
//------------------上面这部分代码则可以生成在一份word----------------------
//------------------将word发送到浏览器下面这部分----------------------------
/* response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
report.process(context, response.getOutputStream());
*/
one.close();