Vue+SpringBoot/SpringCloud轻松实现Excel文件下载

问题还原:

在做项目时,很多时候会用到上传、下载Excel文件。此处,笔者需要实现Excel文件下载功能。具体实现如下所述。

解决方案:

Vue端相关代码如下:
定义按钮:

<el-button
              type="primary"
              icon="el-icon-upload2"
              @click="downloadExcel()"
            >
              下载Excel
            </el-button>

JS方法:

methods: {
downloadExcel () {
// 下载好用版
    Vue.axios({
      method: 'get',
      url: '/***/downloadExcel',
      responseType: 'arraybuffer'
    }).then((response) => {
      console.log('response====================')
      console.log(response)
      const link = document.createElement('a')
      link.style.display = 'none'
      const url = window.URL.createObjectURL(new Blob([response], { type: 'application/vnd.ms-excel' }))
      link.href = url
      link.setAttribute('download', '***.xlsx')
      document.body.appendChild(link)
      link.click()
    }).catch((error) => {
      this.$message.error(error)
    })
    }
  }

SpringBoot/SpringCloud端相关代码如下:
Controller层代码:

@GetMapping("/downloadExcel")
   @ApiOperation(value = "下载Excel")
    public void getExcelData(HttpServletResponse response) throws IOException {
       ExcelUtil.readExcelToIO ("D:\\\\ExcelTest\\\\**.xlsx", response);
    }

ExcelUtil代码如下:

public static void readExcelToIO(String fileName, HttpServletResponse response) throws IOException {
      //判断是否为excel类型文件
      if(!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
      {
          throw new RuntimeException("所传入文件不是Excel文件!");
      }
      //读取Excel文件
      File excelFile = new File(fileName.trim());
      InputStream inputStream = new FileInputStream(excelFile);
      // 构造 XSSFWorkbook 对象,strPath 传入文件路径
      Workbook workbook = null;
      //获取Excel工作薄
      if (excelFile.getName().endsWith("xlsx")) {
          workbook = new XSSFWorkbook(inputStream);
      } else {
          workbook = new HSSFWorkbook(inputStream);
      }
      if (workbook == null) {
          throw new RuntimeException("Excel文件有问题,请检查!");
      }
      // 读取第一个sheet页表格内容
      Sheet sheet = workbook.getSheetAt(0);
      OutputStream os = response.getOutputStream();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
      // 返回数据到输出流对象中
os.write(baos.toByteArray());
      os.flush();
      os.close();
  }

PS:欢迎大家点赞、关注、支持。如有需要,欢迎添加博主QQ沟通交流!QQ:156587607

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值