excel报表生成和下载
生成文件并返回下载路径路径
生成文件接口(业务数据没写进去 下方是文件处理代码)
String uuid = UUID.randomUUID().toString().replace("-", "");
String fileName = uuid + ".xls";
String root = FileUtill.getResourceBasePath();
try {
String path = root + File.separator + "manhours" + File.separator + fileName;
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
FileOutputStream fileOut = new FileOutputStream(path);
workBook.write(fileOut);
fileOut.close();
String pPath = request.getContextPath() + "/manhours/file/" + uuid;
return result = JtsResultUtil.success(pPath);
} catch (Exception e) {
result = JtsResultUtil.success(e.getMessage());
} finally {
workBook.close();
}
下载文件接口
请求上一个接口返回的文件下载路径
(注意文件被下载后会被删除,如果不需要请自行删除finally中判断部分的代码)
@RequestMapping(value = "/file/{fileName}")
public void file(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileName") String fileName) throws IOException, Exception {
InputStream pInputStream = null;
OutputStream os = response.getOutputStream();
// 设置相关格式
response.setContentType("application/force-download");
// 设置下载后的文件名以及header
String fileNameAlias = "月工时表.xls";
fileNameAlias = URLEncoder.encode(fileNameAlias, "utf-8");
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-disposition", "attachment;fileName=" + fileNameAlias);
String rootPath = FileUtill.getResourceBasePath();
String filePath = rootPath + File.separator + "manhours" + File.separator + fileName + ".xls";
File file = new File(filePath);
try {
pInputStream = new FileInputStream(file);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = pInputStream.read(buffer, 0, bufferSize)) != -1) {
os.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pInputStream != null) {
pInputStream.close();
if (file != null && file.exists()) {
file.delete();
}
}
os.flush();
os.close();
}
}