通过输出流将文档下载到本地

/**
* 导出Excel文档到本地

*
* @param path 文件将要保存的目录
*/
@ApiOperation(value = “下载Excel模板”)
@RequestMapping(value = “/downloadDepartment.xls”, method = RequestMethod.GET, produces = {
“application/vnd.ms-excel;charset=UTF-8” })
public void exportExcel(String path) {
OutputStream out = null;
try {
// 获取要下载的模板名称
String fileName = “department.xlsx”;
// 设置要下载的文件的名称
response.setHeader(“Content-disposition”, “attachment;fileName=” + fileName);
// 通知文件类型
response.setContentType(“application/vnd.ms-excel;charset=UTF-8”);
// 获取文件的路径
String filePath = getClass().getResource("/templates/" + fileName).getPath();
FileInputStream input = new FileInputStream(filePath);
// 输出的文件流保存到本地文件
File tempFile = new File(path);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
out = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
byte[] b = new byte[2048];
int len;
while ((len = input.read(b)) != -1) {
out.write(b, 0, len);
}
// 修正 Excel在“xxx.xlsx”中发现不可读取的内容。是否恢复此工作薄的内容?如果信任此工作簿的来源,请点击"是"
response.setHeader(“Content-Length”, String.valueOf(input.getChannel().size()));
input.close();
} catch (Exception e) {
throw new BusinessException(“读取写出异常”);
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

你可能感兴趣的:(下载Excel)