Springboot整合easyExcel

本文介绍如何使用SpringBoot结合easyExcel实现Excel文件的上传与下载功能,包括配置依赖、定义实体类、实现前后端交互及示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

介绍

平时工作中,我们经常都会用到excel文件上传或者下载的问题,比如将表数据导出为excel表格或者进行数据导入数据库等,本篇我们就介绍一下easyExcel进行操作Excel进行web的上传或者下载。

快速开始

<!-- 引入easyexcel依赖-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.1.1</version>
</dependency>

Entity实体类

上传Excel的每个表格对应一行的一个cell,使用注解@ExcelProperty进行标注标题。

/**
 * 列信息实体类
 */
@Data
@TableName("ColumnEntity")
public class ColumnEntity {
    @TableId(value = "column_id", type = IdType.AUTO)
    @ExcelProperty(value="序号")
    private String columnId;
    //列名
    @ExcelProperty(value="列名")
    @TableField("column_name")
    private String columnName;
    //列注释
    @ExcelProperty(value="列注释")
    @TableField("column_desc")
    private String ColumnDesc;
    //类型
    @ExcelProperty(value="数据类型")
    @TableField("column_type")
    private String columnType;
    //长度
    @ExcelProperty(value="长度")
    @TableField("column_len")
    private String columnLen;
    //精度
    @ExcelProperty(value="精度")
    @TableField("precision")
    private String precision;
    //是否主键 Y true 都默认是主键
    @ExcelProperty(value="是否主键")
    @TableField("isPrimaryKey")
    private String isPrimaryKey;
    //是否允许为空 Y true 不允许为空
    @ExcelProperty(value="是否允许为空")
    @TableField("isNotNull")
    private String isNotNull;
    //是否索引列,方便进行生成建表语句的时候进行生成索引
    @ExcelProperty(value="是否索引列")
    @TableField("isIdxCol")
    private String isIdxCol;
}

下载模板

    /**
     * 下载excel模板
     */
    @GetMapping("/downLoadExcelTemplate")
    public void downLoadExcelTemplate(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("实体类模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //空数据
        List<ColumnEntity> columnEntityList = null;
        EasyExcel.write(response.getOutputStream(), ColumnEntity.class).sheet("创建实体类模板").doWrite(columnEntityList);
    }

上传Excel文件

上传Excel我们需要监听读取sheet,EasyExcel会自动解析文件,我们只需要对监听的行进行处理就ok。

监听类

/***
 * easyexcel监听类
 */
@Slf4j
public class ColumnListener implements ReadListener {

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param o
     * @param analysisContext
     */
    @Override
    public void invoke(Object o, AnalysisContext analysisContext) {
        System.out.println(o.toString());
    }

    /**
     * 所有数据解析完成了 都会来调用
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //
        log.info("所有数据解析完成!");
    }
}

上传Excel

    /**
     * 文件上传
     * <p>1. 创建excel对应的实体对象 参照{@link }
     * <p>2. 由于默认一行行的读取excel,所以需要创建excel一行一行的回调监听器,参照{@link }
     * <p>3. 直接读即可
     */
    @PostMapping("/uploadExcel")
    public String importData(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), ColumnEntity.class, new ColumnListener()).sheet().doRead();
        return "success";
    }

前端页面

前端主要使用elementui的上传文件组件进行上传。代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>excel上传下载管理</title>
</head>
<!--script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script-->
<!--引入静态的路径-->
<script type="text/javascript" src="js/vue.min.js"></script>
<!--script src="https://unpkg.com/element-ui/lib/index.js"></script-->
<script type="text/javascript" src="js/index.js"></script>
<!-- 引入样式 -->
<!--link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"-->
<link rel="stylesheet" href="css/index.css">
<!-- 引入组件库 -->
<!--引入通信框架-->
<!--script src="https://unpkg.com/axios/dist/axios.min.js"></script-->
<script type="text/javascript" src="js/axios.min.js"></script>
<body>
<div id="app">
    <h1 style="background-color: #409EFF;text-align: center;">EasyExcel上传下载管理</h1>
    <div>
        <el-form :inline="true"  class="demo-form-inline" label-position="center" >
            <el-form-item>
                <el-button type="primary" icon="el-icon-download" @click="downloadTemplate">下载excel模板</el-button>
                <el-button type="primary" icon="el-icon-upload2" @click="importData">上传excel</el-button>
            </el-form-item>
        </el-form>

        <!---导入弹框-->
        <el-dialog title="上传Excel:上传前先下载模板进行格式调整" :visible.sync="dialogImportVisible" width="480px">
            <!--选择框-->
            <el-form label-position="center" label-width="170px">
                <el-form-item label="文件">
                    <el-upload
                            :multiple="false"
                            :on-success="onUploadSuccess"
                            :action="'http://localhost:8017/uploadExcel'"
                            class="upload-demo">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传xls文件,且不超过500kb</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="info" @click="dialogImportVisible = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</div>
</body>
</html>
<script>
    new Vue({
        el: "#app",
        //数据
        data() {
            return {
                dialogImportVisible:false //导入上传文本框
            }
        },
        //创建之前
        created() {

        },
        //初始化加载数据
        mounted() {

        },
        methods: {
            //导入数据
            importData(){
                this.dialogImportVisible = true
            },
            //下载模板
            downloadTemplate(){
                window.open("http://localhost:8017/downLoadExcelTemplate")
            },
            //加载成功
            onUploadSuccess(response, file) {
                this.$message.info('上传成功')
                this.dialogImportVisible = false
            }
        }

    });
</script>
<style scoped>

</style>

测试

下载
下载模板
上传
后台监听数据:
监听数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小刘同学要加油呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值