参考地址https://www.cnblogs.com/linkworld/p/7636734.html
1. 下载概述
下载就是向客户端响应字节数据! 将一个文件变成字节数组, 使用 response.getOutputStream()
来响应给浏览器!!
2. 下载要求
- 两个头一个流
Content-Type: 传递给客户端的文件的 MIME 类型;
可以使用文件名称调用 ServletContext 的 getMimeType() 方法, 得到 MIME 类型! - Content-Disposition:attachment;filename=xxx:
它的默认值为 inline, 表示在浏览器窗口中打开! attachment 表示附件, filname 后面跟随的是显示在
下载框中的文件名称!
流:要下载的文件数据!
@RequestMapping("/template")
public void template(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.ms-excel");//定义下载文件的类型
response.setHeader("Content-disposition", "attachment;filename=student.xls");//文件名
OutputStream outputStream = response.getOutputStream();//相应的输出流
HSSFWorkbook wk = projectInfoService.template();//生成Excel文件,此处可以换成类型的其他文件
wk.write(outputStream);//把要下载的文件写入到输出流中
wk.close();
outputStream.flush();
outputStream.close();
}
//生成Excel模板
public HSSFWorkbook template() {
String header = "序号,名称,简称,编号,备案号,合同编号,许可证号,性质,日期,备注";
HSSFWorkbook wk = new HSSFWorkbook();
HSSFSheet sheet = wk.createSheet();
HSSFRow row = sheet.createRow(0);
HSSFCellStyle style = wk.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
String[] headers = header.split(",");
for (int i = 0; i < headers.length; i++) {
row.createCell(i).setCellValue(headers[i]);
}
// wk.close();
return wk;
}
java生成Excel需要用到的包
<!-- Excel导入导出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>