SpringBoot+Vue下载Excel文件流(No converter、Excel乱码)

介绍

后端使用SpringBoot、Mybatis Plus,前端使用Vue,进行Excel文件下载。
后端使用了Hutool工具提供的Excel文件流下载。

No converter

问题:
后端控制台出现No converter for [class com.common.lang.Result] with preset Content-Type 'application/vnd.ms-excel;charset=utf-8'的错误
在这里插入图片描述
处理:

原来的代码返回一个对象(包含code、message、data等)。

public Result download (HttpServletResponse response) throws IOException {
//省略
	return Result.succ("success");
}

改为:

public void download (HttpServletResponse response) throws IOException {
//省略
	return;
}

就是把返回的参数类型设置为void,身为小白的我并不清楚原因。

Excel乱码

前端下载的Excel打开后出现:
在这里插入图片描述
于是参考:

https://www.cnblogs.com/yixiaoyang-/p/13042540.html
https://www.cnblogs.com/cynthia-wuqian/p/7927621.html

才得到了正确结果(测试数据):
在这里插入图片描述

正确代码

后端代码

关于Excel的操作可参考Hutool工具提供的Excel文件流下载,比如可以设置文件格式为xls或者xlsx。

 @RequestMapping("/download")
    public void download (@RequestBody Map<String, Object> columnMap,
                            HttpServletResponse response) throws IOException {
        List<String> row1 = CollUtil.newArrayList("aa", "bb", "cc", "dd");
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.write(row1, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=test.xls");
        ServletOutputStream out=response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
        return;
}

前端代码

方法1

其中responseType可以设置为arraybuffer或者blob,必须要设置一个。
elink.download后面的文件名可以随意设置(可中文),可以和后端的文件名不一样,最终会以前端设置的文件名为准,但文件后缀要和后端的xls或xlsx保持一致。

        axios({
          baseURL: "http://localhost:8081/",
          url: "download",
          method: "post",
          data: data,
          // responseType: "arraybuffer", //可以使用arraybuffer
          responseType: "blob",  //也可以使用blob
        })
          .then((res) => {
            console.log(res);
            if (res) {            
              let blob = new Blob([res.data], {
                type: "application/vnd.ms-excel;charset=utf-8",
              }); // res就是接口返回的文件流了
              let objectUrl = URL.createObjectURL(blob);          
              const elink = document.createElement("a");
              elink.download = "下载文件名称.xls"; //下载文件名称,
              elink.style.display = "none";
              elink.href = objectUrl;
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href); // 释放URL 对象
              document.body.removeChild(elink);
            }
          })
          .catch(function (error) {
            console.log(error);
          });

方法2

axios({
          baseURL: "http://localhost:8081/",
          url: "download",
          method: "post",
          data: data,
          // responseType: "arraybuffer",//可以使用arraybuffer
          responseType: "blob", //也可以使用blob
        })
          .then((res) => {
            console.log(res);
            if (res) {
              let blob = new Blob([res.data], {
                type: "application/vnd.ms-excel",
              }); // res就是接口返回的文件流了
              let objectUrl = URL.createObjectURL(blob);
              window.location.href = objectUrl;            
            }
          })
          .catch(function (error) {
            console.log(error);
          });

代码行数减少了,但此时无法设置文件名:
在这里插入图片描述
里面的内容是正确的。

方法3

先引入一个包js-file-download

cnpm install js-file-download --save

使用方法:

var fileDownload = require('js-file-download');
fileDownload(data, '文件名称.xls');

具体代入就是:

		axios({
          baseURL: "http://localhost:8081/",
          url: "download",
          method: "post",
          data: data,
          // responseType: "arraybuffer",//可以使用arraybuffer
          responseType: "blob", //也可以使用blob
        })
          .then((res) => {
            console.log(res);
            if (res) {
              var fileDownload = require("js-file-download");
              fileDownload(res.data, "新方式.xls");             
            }
          })
          .catch(function (error) {
            console.log(error);
          });

与方法一相比,代码更简洁明了,只需要设置文件名。
在这里插入图片描述

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
实现Excel文件上传到数据库有多种方法,以下是一种基于Spring Boot和Vue的实现方式: 1. 前端页面实现 在Vue的前端页面中,添加一个文件上传组件,例如使用element-ui的el-upload组件: ```html <template> <el-upload class="upload-demo" action="/upload" // 文件上传的后端接口 :on-success="handleSuccess" :before-upload="beforeUpload"> <el-button size="small" type="primary">点击上传</el-button> </el-upload> </template> ``` 2. 后端接口实现 在Spring Boot后端实现一个文件上传的接口,例如使用Spring Boot自带的MultipartFile实现: ```java @RestController public class FileUploadController { @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { // 读取Excel文件,解析数据并插入到数据库中 ... return "success"; } } ``` 3. 解析Excel并插入到数据库中 在handleFileUpload方法中,可以使用Apache POI库来解析上传的Excel文件,并将数据插入到数据库中。示例代码如下: ```java Workbook workbook = WorkbookFactory.create(file.getInputStream()); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { String name = row.getCell(0).getStringCellValue(); String age = row.getCell(1).getStringCellValue(); // 将数据插入到数据库中 ... } ``` 这样就可以实现将Excel文件上传到数据库中了。需要注意的是,上传的Excel文件需要符合一定的格式,例如第一列是姓名,第二列是年龄等等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值