根据业务需求,整合数据生成一个word文档
流程:
1、对需要填充数据进行获取,value
2、编写一个.ftl文档,样式为word所需样式
3、把.ftl文件与value进行结合,生成一个html文件
4、html文件转换为word文件
5、文件流形式进行返回
开发流程与分区:
1:整合需要填充的数据(返回前端的数据形式),测试可以使用Map格式的数据--方便;
2:编写.ftl文件设计html样式:整体语法与html没有太大区别;文件名称free_wordtest.ftl
3.:生成html文件 String freeWordtest =“free_wordtest.ftl”;
注意点:
文件地址:测试放本地(String path = this.getclass.getResource("/").getPath+"freemarker/ test/")
(名称记得替换为业务的名称最好保证唯一): String htmlName = “测试”+".html";
1):第一步创建一个Configuration 对象:直接new方法显示废弃,建议使用方式为
Configuration configuration = new Configuration(Configuration.getVersion());
2):第二步设置模板文件所在路径
File file = new File( path);
configuration.setDirectoryForTemlateLoading(file);
3:设置字符集
configuration.setDefaultEncoding("utf-8");
4):加载并创建模板对象
Template template = configuration.getTemplate(freeWordtest );
5):创建写对象
String htmlPath = path +htmlName;
Writer out = new FileWriter(new File(htmlPath));
6).调用模板导入数据 date 为需要填充的数据
template.process(data,out);
out.close();
7):返回地址 return htmlPath;
4:html生成worde :htmlFile html路径;filePath:生成文件地址
BuffereReader buffereReader = new BuffereReader(new FileReader(htmlFile));
StringBuffer stringBuffer = new StringBuffer();
Stream<String> lines = buffereReader.lines();
lines.forEach(item ->{
stringBuffer.append(item);
});
byte htmlContextBytes[] = stringBuffer.toString.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(htmlContextBytes);
POIFSPileSystem poifs = new POIFSFileSystem();
FirectoryEntry directory = poifs.getRoot();
DocumentEntry documentEntry = directory.createDocument("WordDocument",bais);
FileOutputStream ostream = new FileOutputStream(filePath);
poifs.writeFilesstem(ostream);
bais.close();
ostream.close();
//转换为byte
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
poifs.writeFilesystem(byteArrayOutputStream );
if(StringUtils.isEmpty(name)){
name = "名称获取失败";
}
String fileName = name +".doc";
try{
fileName = URLEncoder.encode(fileName,"UTF-8");
}catch(Exception e){
e.printStackTrace();
}
byte[] bytes = byteArrayOutputStream.toByteArray();
File file = new File(filePath);
ResponseEntity.ok.header("Content-Disposition","attachment;filename="+fileName).header("filename",fileName).header("Access-Control-Expose-Headers","fileName").contenType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document")).contentType(MediaType.parseMediaType("application"/octet-stream)).body(bytes);