pageoffice 花钱
poi 设置格式麻烦
freemarker word转xml,xml再转ftl,修改太麻烦
poi-tl (推荐) 简单,操作容易,word设置什么样导出的就是什么样
官网API:http://deepoove.com/poi-tl/http://deepoove.com/poi-tl/http://deepoove.com/poi-tl/
/**
* @Description 文件下载
* @param dataMap
* @param type
* @Throws
* @Return void
* @Date 2021-09-14 15:31:03
* @Author WangKun
**/
public static void downloadFile(Map<String, Object> dataMap,String type, HttpServletResponse response){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
File file = templateCreateDoc(dataMap, Objects.requireNonNull(DocumentEnum.getValue(type)));
response.setContentType("application/msword;charset=utf-8");
if (file != null) {
response.addHeader("Content-Disposition", "attachment; filename=\""
+ new String(file.getName().getBytes(), StandardCharsets.ISO_8859_1) + "\"");
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[10240];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
// 下载完毕删除磁盘文件
if (file.exists()) {
file.delete();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
dataMap:要放到模板里的数据
type:这个是做的枚举类型获取模板名称的,可以直接写模板名称
/**
* @Description 数据组装
* @param
* @Throws
* @Return java.util.Map<java.lang.String,java.lang.Object>
* @Date 2021-09-14 15:46:25
* @Author WangKun
**/
public static Map<String, Object> siteInspectRecordMap() {
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("checkUnit", "");
return dataMap;
}
模板转换代码:
/**
* @Description 模板转换
* @param dataMap
* @param ftlName
* @Throws
* @Return java.io.File
* @Date 2021-09-15 10:33:04
* @Author WangKun
**/
public static File templateCreateDoc(Map<String, Object> dataMap, String ftlName) {
// 获取模板文件地址 utf-8获取 空格不转义
String path = URLDecoder.decode(Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("")).toString().replace('/', '\\').replace("file:", "").replace("classes\\", "").substring(1) + "classes\\template\\", "utf-8");
File file = new File(path+"\\"+ftlName);
if (!file.exists()) {
return null;
}
//调用模板,填充数据
XWPFTemplate template = XWPFTemplate.compile(path+ftlName).render(dataMap);
try {
String fileName = path + ftlName.substring(0, ftlName.indexOf(".")) + ".doc";
File file1 = new File(fileName);
//要导出的文件名
FileOutputStream out = new FileOutputStream(fileName);
template.write(out);
out.flush();
out.close();
template.close();
return file1;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
模板格式:
导出结果:
注意模板的字段值一定要与map中的key对应,否则不可以.