web导出excel文件并下载

通常在项目中我们需要对一些数据进行查询,如果有分析需求可能会需要导出成excel方便整理,下面的代码我们使用springboot框架,结合easyexcel2.2.6完成主要部分代码。

1.后台生成excel文件流

@RequestMapping(value="/api/export",produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public String export(String id,HttpServletResponse response,Model model){
    //TODO 根据需求完成数据查询得到 exportVoList,此处我仅新建一个空集合作为示例
    List<ExportVo> exportVoList = new ArrayList<>();
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("UTF-8");
    try{
        String fileName = URLEncoder.encode("文件名称","UTF-8");
        response.setHeader("Content-disposition","attachment;fileName="+fileName+".xlsx");
        EasyExcel.write(response.getOutputStream(),ExportVo.class).sheet("sheet1")
            //设置列宽自适应,注意自适应不是万能的
            .registerWriteHandler(new LongestMatchColumWidthStyleStrategy())
            .doWrite(exportVoList);
    }catch(Exception e){
        e.printStackTrace();
    }
}

 ExportVo

package com.xxx.xx.xxx.vo

import com.alibaba.excel.annotation.ExcelProperty;
import ...

import java.io.Serializable;

public class ExportVo implements Serializable {
    private static final long serialVersionUID = -1L;
    @ExcelProperty(value= "编号",index = 0)
    private String id;
    @ExcelProperty(value= "名称",index = 1)
    private String name;
    @ExcelProperty(value= "操作",index = 2)
    private String opration;
    
    //TODO getAndSetMethods
    //TODO po2Vo 也可以通过工厂类等其他方式完成
}

2.前端主要js

XMLHttpRequest方式

function downloadExportFile(url) {
    //我在此处加入了遮罩,以防止发生多次重复点击,这部分根据需要实现即可,不同框架可能写法不同...
    var loadMsg = layer.load(2,{shade:[0.3,'#fff']});
    const xhr = new XMLHttpRequest();
    xhr.open("GET",url,true);
    xhr.responseType = 'blob';
    xhr.onload = function (e){
        if(this.status == 200){
            var fileName;
            var fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = fileNameRegex.exec(this.getResponseHeader("Content-disposition"));
            if(matches!=null && matches[1]){
                fileName = matches[1].replace(/['"]/g,"");
                fileName = decodeURI(fileName);
                
                const blob = this.response;
                const reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onload = function (e){
                    const a = document.createElement('a');
                    a.download = fileName;
                    a.href = e.target.result;
                    a.text = fileName;
                    
                    //模拟a标签点击事件,也可以在指定位置插入下载链接,点击即可下载文件 例如 $("#id").after(a);
                    document.documentElement.appendChild(a);
                    a.click();
                    a.remove();
                }
            }
        }else{
            //提示用户下载出错,稍后重试
            layer.msg('下载出错,请稍后重试');
        }
        //关闭遮罩
        layer.close(loadMsg);
    }
    xhr.send();
}

ajax方式

$.ajax({
    type:"POST",
    success:function(result,state,xhr){
        var fileName;
        var fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        var matches = fileNameRegex.exec(this.getResponseHeader("Content-disposition"));
        if(matches!=null && matches[1]){
            fileName = matches[1].replace(/['"]/g,"");
            fileName = decodeURI(fileName);
        }
        //暂未记录
    }
});

 

posted @   一尺灯光  阅读(177)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示