vue + element-ui + springboot上传和下载excel文件

前言

前端用vue

后端使用springboot,解析excel需要的依赖如下:

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>easyexcel</artifactId>
   <version>3.3.2</version>
</dependency>

一、上传excel文件

1.前端

元素:

 <el-upload class="upload-demo"  :before-upload="berforeUpload"         action="">

        <el-button size="small" type="primary">点击上传</el-button>

       <div slot="tip" class="el-upload__tip">只能上传excel文件,且不超过500kb</div>

    </el-upload>

方法:

1.berforeUpload:用来判断是否是excel文件

2.upload:发起请求,传输文件到后端 

//导入请求方法,我的请求方法在"../api/userMG.js"中
import {uploadFile } from '../../api/userMG'
....

berforeUpload(file) {
     
      let suffix = file.name.substring(file.name.lastIndexOf('.') + 1) === "xlsx";

      if(suffix) {
        //必须要把文件放到FormDate里,否则数据传输不到后端
        let form = new FormDate();
        form.append("file", file);
        //发起请求
        this.upload(file)

      }else {
        this.$message({
          type: 'error',
          message: '只允许上传excel文件'
        })
      }
    },


    //上传文件
    upload(file) {
        uploadFile(file)
            .then(res => {
              if (res.success) {
                this.$message({
                  type: 'success',
                  message: '文件上传成功'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('文件上传失败,请稍后再试!')
            })
      }

3.请求代码

注意:使用之前记得导入到对应文件,(我写在src/api/userMG.js文件中,导入为:(

import { productList, productSave, productDelete, uploadFile, exportFile } from '../../api/userMG'

export const uploadFile = (params) => {
    return axios.post('/api/Product/uploadFile', params, {
        headers: {
            'Content-Type': 'multipart/form-data',
            token: localStorage.getItem('logintoken')
        },
    })
}

2.后端

controller代码

@PostMapping(Urls.Product.UPLOAD_FILE)
@ApiModelProperty("文件上传")
public R uploadFile(MultipartFile file) {
    return R.status(productService.uploadFile(file));
}

service代码

/**
 * 上传文件
 *
 * @param file
 * @return
 */
@Override
public boolean uploadFile(MultipartFile file) {

    UploadListener<Product> productUploadListener = new UploadListener<>();
    try {
        EasyExcel.read(file.getInputStream(), Product.class, productUploadListener).sheet().doRead();
        List<Product> data = productUploadListener.getData();
        return super.saveBatch(data);
    } catch (Exception e) {
        throw new ServiceException("文件上传失败");
    }
}

二、下载excel文件

这里我直接默认下载到电脑桌面,并且是覆盖式下载,就是说如果多次点击下载,会删除上一次的文件,再进行下载。

1.前端

 元素:

  <el-button size="small" type="primary" icon="el-icon-download" @click="exportFile">下载</el-button>

方法:

  //导出文件

    exportFile() {

      exportFile()

            .then(res => {

              if (res.success) {

                this.$message({

                  type: 'success',

                  message: "文件已下载到桌面"

                })

              } else {

                this.$message({

                  type: 'error',

                  message: res.msg

                })

              }

            })

            .catch(err => {

              this.loading = false

              this.$message.error('文件下载失败,请稍后再试!')

            })

      }

2.后端 

controller代码

@GetMapping(Urls.Product.EXPORT_FILE)
@ApiModelProperty("文件导出")
public R ExportFile() {
    return R.status(productService.exportFile());
}

service代码

@Override
public boolean exportFile() {
    try {
        String path = FileUtils.getDesktopPath() + "\\";
        String fileName = "库存管理.xlsx";
        //文件如果存在,就进行删除,重新下载一份,相当于覆盖
        FileUtils.existDle(new File(path + fileName));

        List<Product> list = super.list();
        EasyExcel.write(path + fileName, Product.class).sheet().doWrite(list);
        return true;
    } catch (RuntimeException e) {
        throw new ServiceException(e.getMessage());
    } catch (Exception e) {
        throw new ServiceException("文件导出失败");
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值