为满足将对应数据插入到word表格中并导出word模板,下载word模板。
utils的 controller里的方法:
1.利用ResponseEntity 实体进行文件导出,以解决导出文件名称自定,防止乱码的效果。因为 ResponseEntity 可以对http协议的header进行设定来设定编码格式。
public static final String TargetDir = "targetfile" + File.separator;
public static final String DownloadDir = "downloadfile" + File.separator;
public static ResponseEntity<byte[]> fileDownload(File targetfile,
String filename, HttpServletRequest request) {
try {
if (targetfile.exists() && targetfile.isFile()) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);//设置header的contenttype为字节流。
String userAgent = request.getHeader("User-Agent");//通过userAgent判断浏览器类型
byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes()
: filename.getBytes("UTF-8"); // name.getBytes("UTF-8")处理safari的乱码问题,解决文件名乱码问题
String fileName = new String(bytes, "ISO-8859-1");
headers.set(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + fileName + "\"");//设置CONTENT_DISPOSITION使浏览器打开文件下载对话框
byte[] readFileToByteArray = null;
readFileToByteArray = FileUtils.readFileToByteArray(targetfile);
return new ResponseEntity<byte[]>(readFileToByteArray, headers,
HttpStatus.OK);
}
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR)
}
2.获取模板文件路径
//params是一个数据map集合,此数据集合用于将数据插入对应模板的对应位置。然后利用XWPFDocument相关技术操作word文档。
public static String getDocxPath(HttpServletRequest request, String type,
Map<String, String> params) {
Map<String, Object> params1 = new HashMap<String, Object>();
for (Entry<String, String> entry : params.entrySet()) {
params1.put(entry.getKey(), entry.getValue());
}
return getDocxPathIncludePic(request, type, params1);
}
public static String getDocxPathIncludePic(HttpServletRequest request,
String type, Map<String, Object> params) {
Map<String, String> docxMapping = SpringContextHolder
.getBean("docxMapping");
String fileTargetPath = docxMapping.get(type);//此tape为配置文件里的key值。通过key值获得对应模板的名字
String tf = null;
if (fileTargetPath != null) {
File dir = new File(request.get