当前位置:   article > 正文

前后端分离,Excel导出实现_前后端分离使用响应值封装导出excel

前后端分离使用响应值封装导出excel

         本篇博客主要记录一下,springBoot + vue前后端分离的项目,如何实现Excel导出功能,项目代码可以参考之前的一篇博文:springBoot+shiro+vue的学生管理系统(二、总体功能及登录功能)

 

1.添加POI依赖:

  1. <!-- excel导出需要的依赖POI-->
  2. <dependency>
  3. <groupId>org.apache.poi</groupId>
  4. <artifactId>poi</artifactId>
  5. <version>3.6</version>
  6. <exclusions>
  7. <exclusion>
  8. <groupId>javax.servlet</groupId>
  9. <artifactId>servlet-api</artifactId>
  10. </exclusion>
  11. <exclusion>
  12. <groupId>log4j</groupId>
  13. <artifactId>log4j</artifactId>
  14. </exclusion>
  15. </exclusions>
  16. </dependency>

这里同时排除了多余的依赖,因为项目中已经引入了,不然就是重复引入了。

 

2.Excel导出工具类:

  1. package com.qxf.utils;
  2. import org.apache.poi.hssf.usermodel.*;
  3. /**
  4. * @Auther: qiuxinfa
  5. * @Date: 2020/4/23
  6. * @Description: com.qxf.utils
  7. */
  8. public class ExcelUtil {
  9. /**
  10. * 导出Excel
  11. * @param sheetName sheet名称
  12. * @param title 标题
  13. * @param values 内容
  14. * @return
  15. */
  16. public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][]values){
  17. // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
  18. HSSFWorkbook wb = new HSSFWorkbook();
  19. // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
  20. HSSFSheet sheet = wb.createSheet(sheetName);
  21. // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
  22. HSSFRow row = sheet.createRow(0);
  23. // 第四步,创建单元格样式,并设置值表头 设置表头居中
  24. HSSFCellStyle style = wb.createCellStyle();
  25. style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
  26. //声明单元格
  27. HSSFCell cell = null;
  28. //创建标题
  29. for(int i=0;i<title.length;i++){
  30. //创建一个单元格
  31. cell = row.createCell(i);
  32. //给单元格赋值
  33. cell.setCellValue(title[i]);
  34. //给单元格设置样式
  35. cell.setCellStyle(style);
  36. }
  37. //创建内容
  38. if (values != null && values[0].length > 0){
  39. for(int i=0;i<values.length;i++){
  40. //从第二行开始创建数据填充的行,下标为1
  41. row = sheet.createRow(i + 1);
  42. for(int j=0;j<values[i].length;j++){
  43. //将内容按顺序赋给对应的列对象
  44. row.createCell(j).setCellValue(values[i][j]);
  45. }
  46. }
  47. }
  48. return wb;
  49. }
  50. }

 

3.接口有一个前缀/user,没有贴出来了:

  1. /**
  2. * 导出报表,这里get和post请求复用了该方法,仅仅是为了测试
  3. *
  4. * @return
  5. */
  6. @RequestMapping(value = "/export")
  7. @ResponseBody
  8. public void export(@RequestBody(required = false) User user,String username,HttpServletResponse response) throws Exception {
  9. if (user ==null && !StringUtils.isEmpty(username)){
  10. //GET 请求的参数
  11. user = new User();
  12. user.setUsername(username);
  13. }
  14. //获取数据
  15. List<User> list = userService.findAllUser(user);
  16. //excel标题
  17. String[] title = {"姓名", "邮箱", "创建时间", "最近登录时间","角色","是否可用"};
  18. //excel文件名
  19. String fileName = System.currentTimeMillis() + ".xls";
  20. //sheet名
  21. String sheetName = "用户信息";
  22. //没有数据就传入null吧,Excel工具类有对null判断
  23. String [][] content = null;
  24. if (list != null && list.size() > 0){
  25. content = new String[list.size()][title.length];
  26. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  27. for (int i = 0; i < list.size(); i++) {
  28. content[i] = new String[title.length];
  29. User obj = list.get(i);
  30. content[i][0] = obj.getUsername();
  31. content[i][1] = obj.getEmail();
  32. content[i][2] = obj.getCreateTime() == null ? "" : sdf.format(obj.getCreateTime());
  33. content[i][3] = obj.getLastLoginTime() == null ? "": sdf.format(obj.getLastLoginTime());
  34. content[i][4] = obj.getRoleName();
  35. content[i][5] = obj.getEnable()==1 ? "是" : "否";
  36. }
  37. }
  38. //创建HSSFWorkbook
  39. HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content);
  40. //响应到客户端
  41. try {
  42. fileName = new String(fileName.getBytes(), "UTF-8");
  43. response.setContentType("application/vnd.ms-excel;charset=utf-8");
  44. response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
  45. OutputStream os = response.getOutputStream();
  46. wb.write(os);
  47. os.flush();
  48. os.close();
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. }

service层之类的代码就不贴了

 

4.前端代码:

两种导出方式:

  1. <el-form-item>
  2. <el-button type="primary" plain @click="exportUser">blob导出</el-button>
  3. </el-form-item>
  4. <el-form-item>
  5. <el-button type="infor" round @click="exportUserByA">a标签导出</el-button>
  6. </el-form-item>

具体的js方法:

  1. // 导出用户,通过blob
  2. exportUser () {
  3. axios({
  4. method: 'post',
  5. url: 'http://192.168.43.152:8089/user/export',
  6. data: {
  7. username: this.filters.keyword
  8. },
  9. responseType: 'blob'
  10. }).then((res) => {
  11. console.log(res)
  12. const link = document.createElement('a')
  13. let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
  14. link.style.display = 'none'
  15. link.href = URL.createObjectURL(blob);
  16. console.log("href:"+link.href)
  17. let num = ''
  18. for(let i=0;i < 10;i++){
  19. num += Math.ceil(Math.random() * 10)
  20. }
  21. link.setAttribute('download', num + '.xls')
  22. document.body.appendChild(link)
  23. link.click()
  24. document.body.removeChild(link)
  25. }).catch(error => {
  26. console.log(error)
  27. })
  28. },
  29. // 导出用户,通过a标签
  30. exportUserByA () {
  31. let username = this.filters.keyword
  32. const link = document.createElement('a')
  33. link.href = "http://192.168.43.152:8089/user/export?username="+username
  34. document.body.appendChild(link)
  35. link.click()
  36. document.body.removeChild(link)
  37. },

 

其实用a标签简单很多

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/770439
推荐阅读
相关标签
  

闽ICP备14008679号