springboot(七):springboot如何实现文件下载

我们来赖回顾一下,上期所讲的内容是使用spring boot进行文件的上传管理,

比如在实际开发我们在前端所用到的图片文件,就需要将文件上传到服务器上,

要用的时候在去拿,这样就减少了本地内存的占用,

这里有个推荐七牛云大家可以去了解一下,对于文件的管理很有效果

介绍

开始今天的知识点,今天要说的是springboot去下载自己生成的xls文件,

我们将从数据库查询到的数据放入lxs文件中,并下载下来,下面看详细实例:

一、在pom.xml加入以下依赖



	org.apache.poi
	poi
	3.13


	org.apache.poi
	poi-ooxml
	3.15

二、在controller层写入以下代码,至于查询的方法需要大家自己写,查询出来加入进去就可以了

/**
 * 文件下载 
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "UserExcelDownloads", method = RequestMethod.GET)
public String downloadAllClassmate(HttpServletResponse response) throws Exception {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet();
    //设置样式
    HSSFCellStyle dateCellStyle = workbook.createCellStyle();
    dateCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
    //创建标题的显示样式
    HSSFCellStyle headerStyle = workbook.createCellStyle();
    headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
   
    //查询数据
    List> classmateList = userService.queryList();

    String fileName = "userinf"  + ".xls";//设置要导出的文件的名字
    //新增数据行,并且设置单元格数据
    int rowNum = 1;
    String[] headers = { "学号", "姓名", "年龄", "生日"};
    //headers表示excel表中第一行的表头
    HSSFRow row = sheet.createRow(0);
    //在excel表中添加表头

    for(int i=0;i teacher : classmateList) {
        HSSFRow row1 = sheet.createRow(rowNum);
        row1.createCell(0).setCellValue((Integer) teacher.get("id"));
        row1.createCell(1).setCellValue((String) teacher.get("usename"));
        row1.createCell(2).setCellValue((Integer) teacher.get("age"));
        row1.createCell(3).setCellValue((String) teacher.get("birthday"));
        rowNum++;
    }

    response.setContentType("application/octet-stream");
    response.setHeader("Content-disposition", "attachment;filename=" + fileName);
    response.flushBuffer();
    workbook.write(response.getOutputStream());
    
	return "login";
}

三·、上面两步骤完成以后,然后你就直接去屌用接口下载了

四、如果使用本人自己的项目,访问地址如下:

      http://localhost:8090/login  UserName:admin  UserPassword:12345

GitHub源码地址:https://github.com/APassionMy/github.springboot-two

上一篇:springboot(六):spingboot如何实现文件上传

你可能感兴趣的:(JAVA,Springboot,spingboot)