Springboot + Vue + axios实现excel的导出下载

本文详细介绍了如何使用Java后端配合Apache POI库实现数据导出至Excel的功能,包括Maven依赖配置、Controller及Service层代码示例。同时,提供了Vue.js前端通过Axios发起请求并处理响应,实现文件下载的完整流程。解决了跨域问题,确保正确获取文件名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后端代码

pom

       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.17</version>
        </dependency>

controller

 @RequestMapping("downloadExcel")
    @ResponseBody
    public void downloadExcel(HttpServletResponse response){
        try {
            goodService.exportDataToEx(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

service

 public void exportDataToEx(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("商品信息表");
        List<Good> goodList = goodMapper.getAllExcelGood();
        // 设置要导出的文件的名字
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "goodinfo"  + sf.format(new Date()) + ".xls";

        // 新增数据行,并且设置单元格数据
        int rowNum = 1;
        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = { "ID", "商品条码", "名称", "类型","规格","建议零售价","我的零售价","库存预警量"};
        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        //在表中存放查询到的数据放入对应的列
        for (Good item : goodList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(item.getId());
            row1.createCell(1).setCellValue(item.getBarcode());
            row1.createCell(2).setCellValue(item.getTitle());
            row1.createCell(3).setCellValue(item.getTypeid());
            row1.createCell(4).setCellValue(item.getWeight());
            row1.createCell(5).setCellValue(item.getPrice());
            rowNum++;
        }
        response.setContentType("application/octet-stream");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        OutputStream outputStream = response.getOutputStream();
        workbook.write(response.getOutputStream());
        outputStream.flush();
        outputStream.close();
    }

Vue前端代码

      axios({
          method: 'post',
          url:requesturl,
          responseType: 'blob'
        })
      .then(res => {
        const filename = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]) || '商品信息表.xls'
        const blob = new Blob([res.data], {
        type: 'application/octet-stream'
      })
        let url = window.URL.createObjectURL(blob);
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click()
      })

遇到的问题

1.response返回了包含响应头所带的所有数据,可以使用console.log(response)查看打印数据,但是打印出来的数据只能拿到默认的响应头,这里有个需要注意的地方。

Cache-Control

Content-Language

Content-Type

Expires

Last-Modified

Pragma

如果想让浏览器能访问到其他响应头的话,需要后端在服务器上设置Access-Control-Expose-Headers

 response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
 response.setHeader("Content-disposition", "attachment;filename=" + fileName);

这样response.headers[‘content-disposition’].split(’;’)[1].split(’=’)[1] 就能取到接口返回的文件名称了。

可以使用Apache POI库来实现在Spring Boot和Vue导出Excel。具体步骤如下: 1. 在后端使用POI库创建Excel文件并填充数据。 2.Excel文件转换为字节数组。 3. 在前端使用axios发送POST请求,将字节数组作为响应体返回。 4. 在前端使用file-saver库将响应体保存为Excel文件。 以下是一个简单的示例代码: 后端代码: ```java @GetMapping("/export") public ResponseEntity<byte[]> exportExcel() throws IOException { // 创建Excel文件并填充数据 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("Hello World!"); // 将Excel文件转换为字节数组 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); byte[] bytes = outputStream.toByteArray(); // 设置响应头 HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", "example.xlsx"); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } ``` 前端代码: ```javascript import axios from &#39;axios&#39;; import { saveAs } from &#39;file-saver&#39;; export function exportExcel() { axios({ url: &#39;/api/export&#39;, method: &#39;GET&#39;, responseType: &#39;arraybuffer&#39; }).then(response => { const blob = new Blob([response.data], { type: &#39;application/vnd.ms-excel&#39; }); saveAs(blob, &#39;example.xlsx&#39;); }); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值