vue简单下载

1.后台代码

 @PostMapping("/downloadList")
    public void downloadList(@RequestBody ApiRequestUtil<Map<String, Object>> request, HttpServletResponse response) throws Exception {
        //可有可无的校验
        ApiResponseCode errorCode = ParamsUtil.checkSecurity(request, md5Key, true);
        if (ApiResponseCode.SUCCESS == errorCode) {
            errorCode = sysUserService.authorityVerify(request.getData().get(ParamsConst.TOKEN).toString());
            if (errorCode != ApiResponseCode.SUCCESS) {
                throw new Exception(String.valueOf(errorCode));
            }
            //获取数据
            String recruitId = ParamsUtil.getAndCheck(request.getData(), "recruitId", false);
            String doctorId = ParamsUtil.getAndCheck(request.getData(), "doctorId", false);
            String status = ParamsUtil.getAndCheck(request.getData(), "status", false);
            List<Map<String, Object>> replyList = rwsPatientCaseService.queryRecruitReplyList(recruitId, doctorId, status);
            //设置分页数据
            RwsPatientCaseHandler.download(replyList,response);
        } else {
            throw new Exception(String.valueOf(errorCode));
        }
    }

2.handler

package com.fn.health.download.rwsPatientCase;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.fn.health.common.domain.DownloadResultDomain;
import com.fn.health.common.utils.WebUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class RwsPatientCaseHandler {

    public  static void download(List<Map<String, Object>> replyList, HttpServletResponse response){
        List<RwsPatientCaseExcel> excelList=RwsPatientCaseExcel.ToList(replyList);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        EasyExcel.write(out, RwsPatientCaseExcel.class).sheet("导出数据").doWrite(excelList);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(out.toByteArray());
        DownloadResultDomain downloadResultDomain = new DownloadResultDomain("患者数据.xlsx", byteArrayInputStream);
        WebUtil.downloadFile(response, downloadResultDomain);
    }
}


3. easyexcel文件

package com.fn.health.download.rwsPatientCase;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.annotation.ExcelProperty;
import com.fn.health.common.Constant;
import com.fn.health.model.RwsGlobalVariable;
import com.fn.health.service.RwsGlobalVariableService;
import com.fn.health.service.RwsPatientCaseService;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Data
public class RwsPatientCaseExcel {
    @ExcelProperty(value = "推荐医生id")
    private String doctorId;
    @ExcelProperty(value = "病例姓名")
    private String patientName;
    @ExcelProperty(value = "病例征集id")
    private String recruitId;
    @ExcelProperty(value = "病例征集标题")
    private String recruitTitle;
    @ExcelProperty(value = "状态")
    private String statusText;
    @ExcelProperty(value = "创建时间")
    private String createTime;

    public static RwsPatientCaseExcel entityToExcel(Map<String, Object> rwsPatientCase,List<RwsGlobalVariable> rwsGlobalVariableList){
        Optional<RwsGlobalVariable> rwsGlobalVariableGet=rwsGlobalVariableList.stream().filter(x->x.getValue().equals(String.valueOf(rwsPatientCase.get("status")))).findFirst();
        if(rwsGlobalVariableGet.isPresent()){
            rwsPatientCase.put("statusText", rwsGlobalVariableGet.get().getText());
        }
        RwsPatientCaseExcel excel=new RwsPatientCaseExcel();
        excel.setDoctorId(String.valueOf(rwsPatientCase.get("doctorId")));
        excel.setPatientName(String.valueOf(rwsPatientCase.get("patientName")));
        excel.setRecruitId(String.valueOf(rwsPatientCase.get("recruitId")));
        excel.setRecruitTitle(String.valueOf(rwsPatientCase.get("recruitTitle")));
        excel.setStatusText(String.valueOf(rwsPatientCase.get("statusText")));
        excel.setCreateTime(String.valueOf(rwsPatientCase.get("createTime")));
        return excel;
    }
    public static List<RwsPatientCaseExcel> ToList(List<Map<String, Object>> mapList){
        RwsGlobalVariableService rwsGlobalVariableService= SpringUtil.getBean(RwsGlobalVariableService.class);
        List<RwsGlobalVariable> rwsGlobalVariableList=rwsGlobalVariableService.getGlobalVariable();
        List<RwsPatientCaseExcel> excelList=new ArrayList<>();
        for (Map<String, Object> entity: mapList) {
            RwsPatientCaseExcel excel=entityToExcel(entity,rwsGlobalVariableList);
            excelList.add(excel);
        }
        return excelList;
    }
}

4.开始搞前台,先写个配置文件

这是之前一人写的,我加了一个download方法

import request from "./request.js"
function toQueryPair(key, value) {
	if (typeof value == 'undefined'){
		return key;
	}
	return key + '=' + encodeURIComponent(value === null ? '' : String(value));
}
function toQueryString(obj) {
	var ret = [];
	for(var key in obj){
		key = encodeURIComponent(key);
		var values = obj[key];
		if(values && values.constructor == Array){//数组
			var queryValues = [];
			for (var i = 0, len = values.length, value; i < len; i++) {
				value = values[i];
				queryValues.push(toQueryPair(key, value));
			}
			ret = ret.concat(queryValues);
		}else{ //字符串
			ret.push(toQueryPair(key, values));
		}
	}
	if(ret.length===0) return ''
	return '?'+ret.join('&');
}
export default{
	token:"",
	width:'',
	port:'',
	login(url,data){
		return request.login(request.url+url,data)
	},
	getdata(url,data,config={}){
		config.headers = { token: this.token }
		return request.getdata(request.url+url,data,config)
	},
	getdataToQuery(url,data,config={}){
		config.headers = { token: this.token }
		return request.getdata(request.url+url+toQueryString(data),{},config)
	},
	getdataForGet(url,data,config={}){
		config.headers = { token: this.token }
		return request.getdataForGet(request.url+url+toQueryString(data),config)
	},
	getimg(url){
		return request.getimg(request.url1+url)
	},
	settoken(token){
		this.token=token
	},
	setwidth(width){
		this.width=width
	},
	setport(port){
		this.port=port
	},
	getmap(url){
		return axios.get(request.urlT+url).then(res=>{
			return res
		})
	},
	photodebug(url, data, config){
		return axios.post(request.urlT+url, data, config).then(res=>{
			return res
		})
	},

	download(url,params){
		return axios.post(request.url+url,params,{responseType:'blob'})
	},
}

5.写个按钮

			<div class="search2">
				<el-button type="success" class="btn" @click="downloadList">下载</el-button>
			</div>

6.点击事件

downloadList(){
				this.download(this.value=="请选择分类"?"1":this.value,this.recruitId==""?"1":this.recruitId,this.doctorId==""?"1":this.doctorId,-1)
			},
			download(value,recruitId,doctorId,index){
				this.tableData=[]
				this.list=[]
				var data = {
					"sign": 0,
					"data": {
						"pn": this.pageindex,
						"ps": this.pagesize,
						'token': this.common.token,
						"timestamp": new Date().getTime()
					}
				}
				if(value!=1){
					data.data.status=value
				}
				if(recruitId!=1){
					data.data.recruitId=recruitId
				}
				if(doctorId!=1){
					data.data.doctorId=doctorId
				}
				var url="patientcase/downloadList"
				this.common.download(url, data).then(res => {
					const type = res.headers['content-type']
					let BLOB = new Blob([res.data], { type: type });
					let url = window.URL.createObjectURL(BLOB);
					let link = document.createElement('a');
					link.style.display = 'none';
					link.href = url;
					link.setAttribute('download', "患者.xlsx")
					document.body.appendChild(link);
					link.click();
				})
			},

7.总结

这个是前端贴的原来一个人的代码,自己改了一点,没大改,还可以封装很多,比如download之后的返回,还有一些传参,都可以封装的,或者写的更优雅,附一段之前同事写的前端同步下载

      window.open(
        `/api/blade-system/taskUpload/downloadTemplate?${
          this.website.tokenHeader
        }=${getToken()}&businessType=data_agency_employee`
      );

有时间就封装封装,写的优雅些

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值