欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot+vue+easyexcel导出

程序员文章站 2022-03-15 09:51:03
...

Springboot

添加 easyexcel 依赖

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

Java 代码

Controller

    @ApiOperation(value = "救治管理数据导出", notes = "救治管理数据导出")
    @PostMapping("cureListDownLoad")
    public void cureListDownLoad(@RequestBody  Map<String,String> map,
                                 HttpServletResponse response) throws IOException {

        String fileNamePrefix = "救治管理综合数据";
        //获取数据
        List<CureDownloadData> cureList = inhosRecordService.getCureListDownLoad(Integer.parseInt(map.get("direct")));
        //导出excel
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(fileNamePrefix , "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8" + fileName + ExcelTypeEnum.XLSX.getValue());
        EasyExcel.write(response.getOutputStream(), CureDownloadData.class)
                .sheet(fileNamePrefix)
                .doWrite(cureList);

    }

Entity

@Data
@ColumnWidth(25)
public class CureDownloadData {

    @ApiModelProperty(value = "姓名")
    @ExcelProperty("姓名")
    private String patientName;

    @ApiModelProperty(value = "证件号码")
    @ExcelProperty("证件号码")
    private String patientCardValue;

    @ApiModelProperty(value = "市/区")
    @ExcelProperty("市/区")
    private String areaName;

    @ApiModelProperty(value = "患者类型")
    @ExcelProperty("患者类型")
    private String dictReferralName;
}

vue

post请求方法封装 ,导出时直接调用该方法

// 封装axios的下载数据流转换成excel
export function DownLoadToExcel(url, data = {}, fileName) {
    fileName = fileName + '.xlsx'
    return new Promise((resolve, reject) => {
        axios
            .post(url, data, {
                responseType: 'blob'
            })
            .then(response => {
                const blob = new Blob([response.data], {
                    type: 'application/vnd.ms-excel'
                })
                if ('download' in document.createElement('a')) {
                    // 非IE下载
                    const elink = document.createElement('a')
                    elink.download = fileName
                    elink.style.display = 'none'
                    elink.href = URL.createObjectURL(blob)
                    document.body.appendChild(elink)
                    elink.click()
                    URL.revokeObjectURL(elink.href)
                    document.body.removeChild(elink)
                } else {
                    // IE10+下载
                    navigator.msSaveBlob(blob, fileName)
                }
                resolve()
            })
            .catch(error => {
                console.log(error)
                reject(error)
            })
    })
}
相关标签: java excel vue