基于SpringBoot-Vue-EasyExcel实现的Excel文件导出+导入_springboot+vue如何在java中生成excel文件,并在vue前端导出,不使用任何第三方-程序员宅基地

技术标签: excel  Vue  SpringBoot  

一:easyExcel依赖

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

二:javaBean

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Users {
    
    private String id;

    @ExcelProperty(value = {"用户姓名"}, index = 1)
    private String name;

    @ExcelProperty(value = {"用户年龄"}, index = 2)
    private String age;

}

三:Controller

@PostMapping ("/excel")
    public void export(HttpServletResponse response, HttpServletRequest request) {
        ServletOutputStream outputStream = null;

        // excel头策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 11);
        headWriteFont.setBold(false);
        headWriteCellStyle.setWriteFont(headWriteFont);

        // excel内容策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontHeightInPoints((short) 11);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        // 设置handler
        HorizontalCellStyleStrategy styleStrategy =
            new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        // Data
        List<Users> list = new ArrayList<>();
        list.add(new Users("1", "小明", "11"));
        list.add(new Users("2", "小红", "11"));
        list.add(new Users("3", "小白", "11"));
        list.add(new Users("4", "小绿", "11"));
        list.add(new Users("5", "小灰", "11"));

        try {
            outputStream = response.getOutputStream();
            EasyExcel.write(outputStream, Users.class)
                .sheet()
                .registerWriteHandler(styleStrategy)
                .doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

四:vue代码

       exportExcel() {
            axios({
                    method: 'post',
                    url: '/excel',
                    responseType: 'blob',
                }
            ).then(function (response) {
                let blob = new Blob([response.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
                let downloadElement = document.createElement('a');
                let href = window.URL.createObjectURL(blob); //创建下载的链接
                downloadElement.href = href;
                downloadElement.download = '哈哈哈.xlsx'; //下载后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); //点击下载
                document.body.removeChild(downloadElement); //下载完成移除元素
                window.URL.revokeObjectURL(href); //释放掉blob对象

            }).catch(function (error) {
                this.$message.error(error)
            });
        }

在这里插入图片描述
在这里插入图片描述

五:导入

5.1:excel监听器

public class WebStudentListener<T> extends AnalysisEventListener<T> {
    
    public final Logger log = LoggerFactory.getLogger(this.getClass());

    public List<T> list = new ArrayList<>();
    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
    
        log.info("读取表格[{}]",t);
        System.out.println(t.toString()+"t");
        list.add(t);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    

    }
    public List<T> getExcelData(){
    
        return list;
    }
}

5.2 接口

    @PostMapping("/redexcel")
    @ResponseBody
    public List<Users> redExcel(HttpServletResponse response, HttpServletRequest request, MultipartFile multipartFile) throws IOException {
    
        InputStream inputStream = multipartFile.getInputStream();
        WebStudentListener<Users> studentWebStudentListener = new WebStudentListener<>();
        EasyExcel.read(inputStream,Users.class,studentWebStudentListener).sheet().doRead();
        List<Users> excelData = studentWebStudentListener.getExcelData();
        return excelData;
    }

5.3 前端组件element upload

        <el-upload
            class="upload-demo"
            action="http://localhost:8082/redexcel"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="uploadSuccess"
            multiple
            name="multipartFile"
            :limit="3">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
        </el-upload>
           uploadSuccess (response, file, fileList) {
    
            console.log(response)
           },
           
           handleRemove (file, fileList) {
    
            console.log(file, fileList)
           },
           
           handlePreview (file) {
    
            console.log(file)
           },
           
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/JasonZhang1416/article/details/108077619

智能推荐

mmdetection3d 源码学习 mvxnet(多模态融合)-程序员宅基地

文章浏览阅读5k次。mmdetection3d 源码学习 mvxnet(多模态融合)配置文件dv_mvx-fpn_second_secfpn_adamw_2x8_80e_kitti-3d-3class.py模型# model settingsvoxel_size = [0.05, 0.05, 0.1]point_cloud_range = [0, -40, -3, 70.4, 40, 1]##模型 图像:主干 ResNet,neck FPN;点云:voxel编码,主干second(稀疏编码),neck secon_mvxnet

C++操作Mysql数据库/Linux下_c++ 操作mysql数据库-程序员宅基地

文章浏览阅读3.3k次,点赞14次,收藏36次。想用C++写项目,数据库是必须的,所以这两天学了一下C++操作Mysql数据库的方法。也没有什么教程,就是在网上搜的知识,下面汇总一下。 连接MySQL数据库有两种方法:第一种是使用ADO连接,不过这种只适合Windows平台;第二种是使用MySQL自己的C API函数连接数据库。我是在Linux平台下开发,所以就采用第二种方法,有很多Api函数,但是常用的就几个,我也是就用到其中的几个。API函_c++ 操作mysql数据库

在Watir中调用JavaScript脚本_watir执行脚本-程序员宅基地

文章浏览阅读3.9k次。如何在Watir中调用JavaScript脚本?下面的脚本实现了此功能,主要原理是通过IE访问Document,再访问parentWindow,最终还是由IE在执行JavaScript脚本: require watir#定义调用JS的类方法class Watir::IE def run_script(js) ie.Document.parentWindow.execS_watir执行脚本

为什么不能使用Thread.stop()方法?_禁止使用thread.stop()来终止线程-程序员宅基地

文章浏览阅读2.1k次。从SUN的官方文档可以得知,调用Thread.stop()方法是不安全的,这是因为当调用Thread.stop()方法时,会发生下面两件事:1. 即刻抛出ThreadDeath异常,在线程的run()方法内,任何一点都有可能抛出ThreadDeath Error,包括在catch或finally语句中。2. 释放该线程所持有的所有的锁 当线程抛出ThreadDeath异常时,会导致_禁止使用thread.stop()来终止线程

神秘魔术动作能量冲击波特效音效Arcane Forces第一套 MAGIC - ARCANE FORCES DESIGNED_magic – arcane forces-程序员宅基地

文章浏览阅读222次。神秘魔术动作能量冲击波特效音效Arcane Forces第一套 MAGIC - ARCANE FORCES DESIGNED原文地址:https://www.aeziyuan.com/t-20646.html文件格式:.WAV文件大小:1.26 GB(解压包大小)文件数量:124音频码率:96kHz, 24-bit音效适用于任何音/视频后期编辑软件,直接导入即可使用包含:酸,奥术,障壁,呼吸,增益,诅咒,减伤,神圣,电,能量,火,玻璃,冰,冲击,光,液体,金属,加工,抛射,隆隆声,序,召唤,._magic – arcane forces

commons-io工具包的基本使用_ioutils.tobytearray-程序员宅基地

文章浏览阅读4w次,点赞57次,收藏304次。目录一、工具类IOUtils的使用:FileUtils的使用:FilenameUtils的使用FileSystemUtils的使用:二、输入、输出三、Filters过滤器四、Comparators比较器五、Monitor文件监控简介:java io操作是开发中比较常用的技术,但是如果每次都使用原生的IO流来操作会显得比较繁琐。Common IO 是一..._ioutils.tobytearray

随便推点

CI867AK01丨Modbus TCP接口模件丨3BSE092689R1-程序员宅基地

文章浏览阅读450次,点赞4次,收藏6次。CI867AK013BSE092689R1Modbus TCP接口模件模块,通过无线或有线的方式,实现设备之间的数据传输和通信连接。

PySide2入门--PySide2介绍与配置-程序员宅基地

文章浏览阅读2w次,点赞16次,收藏96次。前言 因为有对GUI界面开发的需求,我前些阵子接触过Qt,一套著名的跨平台的C++图形界面框架。Qt开发最有效的Qt creator,跨平台且集成多款工具,上手体验十分友好。但是,由于C++导入第三方库相对麻烦,而且现有的代码都基于Python实现。此处将介绍Qt相应的Python模块——PySide。为什么不选择PyQt? PySide2和PyQt5同样对应的Qt5框架,PyQt甚至要比PySide出现更早,社区更完备、中文文档更丰富。但是,值得注意的是:二者的许可证存在着差异。 PyQ_pyside2

Jupyter Notebook如何调试?JupyterLab作为DeBug调试工具及调试教程_jupyterlab怎么debug-程序员宅基地

文章浏览阅读2.9w次,点赞30次,收藏107次。引言xeus-python是2020年新出的Jupyter notebook调试工具,参考机器之心的文章首款 Jupyter 官方可视化 Debug 工具,JupyterLab 未来可默认支持 Debug安装过程安装JupyterLab 前端插件jupyter labextension install @jupyterlab/debugger安装xeus-python作为后端kernelconda install xeus-python -c conda-forge调试教程只要装好前端与_jupyterlab怎么debug

如何将xml转换为json_xml转json-程序员宅基地

文章浏览阅读3.8k次。<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160807</version> </dependency>导入 json-20160807.jar jar包 直接调用 XML.toJSONObject(“xml内容”) 就可以把XML._xml转json

TCP 的那些事 | TCP报文格式解析_.tcp文件是图片吗-程序员宅基地

文章浏览阅读1.3k次。TCP(Transmission Control Protocol 传输控制协议)提供一种面向连接的、可靠的字节流服务。面向连接意味着两个使用TCP的应用(通常是一个客户和一个服务器)在彼此交换数据之前必须先建立一个TCP连接。TCP在网络ISO的七层模型中的第四层---Transport层,在TCP/IP协议中的第三层---传输层。TCP通过下列方式来提供可靠性:1. 应用数据被分..._.tcp文件是图片吗

python——stack()和unstack()用法_unstack函数-程序员宅基地

文章浏览阅读1.2w次,点赞12次,收藏54次。在学习python的过程中遇到了这两个函数,讲讲学习的心得_unstack函数

推荐文章

热门文章

相关标签