栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

问题还原:

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

解决方案:

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


              下载Excel
            

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/711113.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号