-->

导入Excel到数据库----springboot

- 第一步

导入eaesyexcel依赖

// excel
    implementation 'org.apache.poi:poi:5.2.2'
    implementation 'org.apache.poi:poi-ooxml:5.2.2'
    implementation 'com.alibaba:easyexcel:3.1.1'

这里的依赖是gradel项目的,如果有其他需要,可以去Maven仓库自己找
Maven仓库官网
进入后搜索需要的依赖项,点击对应的版本进行复制
image
image
image

编程

序列化对象类里面

//@Data自动生成get和set等方法,不包括构造函数
@Data
//@TableName确定对应的数据库表格,可以不写
@TableName("dct_flowfee")
public class Flowfee {

    @TableId(type = IdType.AUTO)
    private Integer id;
//@NotBlank用于参数校验,表示该属性不能为空格  @NotNull用于参数校验,表示该属性不能没有@ExcelProperty用于excel导入,excel第一列名称为“快递公司名称”
    @NotBlank(message = "name不能为空")
    @NotNull(message = "name不能为空")
    @ExcelProperty("快递公司名称")
    private String name;

    @NotBlank(message = "addrfrom不能为空")
    @NotNull(message = "addrfrom不能为空")
    @ExcelProperty("出发地")
    private String addrfrom;

    @NotBlank(message = "addrto不能为空")
    @NotNull(message = "addrto不能为空")
    @ExcelProperty("到达地")
    private String addrto;

    @NotNull(message = "max不能为空")
    @ExcelProperty("最高公斤数")
    private int max;

    @NotNull(message = "fee不能为空")
    @ExcelProperty("费用")
    private int fee;

    @ExcelProperty("备注")
    private String remark;

    @ExcelProperty("创建时间")
    private LocalDateTime created;

}

- 第二步

Service里面

@SneakyThrows
    public boolean importFileToDB(boolean deleteHistory, MultipartFile file) {
//是否删除数据库表中历史数据
        if (deleteHistory) {
            this.remove(null);
        }
//读取excel表格中数据
        EasyExcel.read(file.getInputStream(), Flowfee.class, new ReadListener<Flowfee>() {
//定义一个常量BATCH_SIZE与一个列表ls
            private static final int BATCH_SIZE = 1000;
            private List<Flowfee> ls = Lists.newArrayList();
//重写invoke方法
            @Override
            public void invoke(Flowfee data, AnalysisContext context) {
                //System.err.println(data);
//列表里添加Flowfee类的数据
                ls.add(data);
//每1000条放到数据库里面
                if (ls.size() >= BATCH_SIZE) {
                    FlowfeeService.this.saveBatch(ls);
                    ls.clear();
                }
            }
//重写doAfterAllAnalysed方法,处理剩下的数据,例如1050条,其中1000条在上面已经放到数据库,剩下的50条下面处理
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                FlowfeeService.this.saveBatch(ls);
            }
        }).sheet().doRead();
        return true;
    }

上面new ReadListener用的jar包为import com.alibaba.excel.read.listener.ReadListener;

- 第三步

准备Result类

@Data
public class Result {
    private String code;
    private String msg;
    private Object data;
    private Exception e;
}

Controller里面

//@PostMapping定义IP地址映射方法与位置,@ApiOperation是swagger测试注解
    @PostMapping("/upload")
    @ApiOperation("Excel导入数据")
    public ReturnResult excelToDatabase(@ApiParam(value = "是否删除全部历史记录", type = "boolean") @RequestParam boolean deleteHistory,
                                  @ApiParam(value = "上传文件", type = "_file") @RequestPart("file") MultipartFile file) {
        Result result = new Result();
        if(flowfeeService.importFileToDB(deleteHistory, file)){
            return ReturnResult.buildSuccessResult("添加成功",null);
        }else {
            return ReturnResult.buildFailureResult("添加失败",null);
        }
    }

注意:@ApiOperation与@ApiParam是swagger的注解,用于测试,如果不需要可以去除

- 第四步

前端JavaScript方法

<!--excel导入数据-->
        layui.use(['upload', 'element', 'layer'], function () {
        var $ = layui.jquery
        , upload = layui.upload
        , element = layui.element
        , layer = layui.layer;

        //常规使用
        var uploadInst = upload.render({
        elem: '#excelUpLoad'
        , url: '/flowfees/upload' //上传接口
        , accept: 'file'
        , data:{
        deleteHistory:"true"
    }
        , exts: 'xls|xlsx|xlsm|xlt|xltx|xltm'
        , done: function (res) {
        if (res.code == "200") {
        layer.msg(res.msg, {icon: 1});
        selectAll();
        fenye();
    } else {
        layer.msg(res.msg, {icon: 2});
        console.log(res.e)
    }
    }
        , error: function () {
        layer.msg("上传失败", {icon: 2});
    }
    });
    });

- 第五步

前端界面

<div class="d-lg-flex align-items-center mb-4 gap-3">
                                <div class="position-relative">
                                    <button type="button" class="layui-btn layui-btn-primary" id="excelUpLoad">
                                        <svg class="icon" aria-hidden="true" style="font-size: 20px;">
                                            <use xlink:href="#icon-excel-ext"></use>
                                        </svg>
                                        Excel导入数据
                                    </button>
                                </div>
                            </div>
posted @ 2022-10-10 22:31  ꧁ʚ星月天空ɞ꧂  阅读(443)  评论(0)    收藏  举报