1 Star 4 Fork 3

大鹏 / easyexcel-spring-boot-starter

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

概述

基于 easyexcel 实现的 spring-boot-starter, 支持 Web 环境下通过 @ExcelParam@ExcelResponse 注解导入和导出 Excel,支持导入时的参数校验,适用于比较简单的导入导出场景。

依赖引入

依赖暂未上传至中央仓库,请自行打包上传到私有仓库。


<dependency>
    <groupId>com.zzuhkp</groupId>
    <artifactId>easyexcel-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

导入

1. 待导入 Excel 文件

文件内容如下:

excel 文件内容

2. 定义 Model 类

定义 Excel 文件内容对应的 Model 类,可使用 easyexcel 注解定义映射关系。


@Data
public class DemoData {

    @ExcelProperty(index = 0)
    private Integer integer;

    @ExcelProperty(index = 1)
    private String string;

    @ExcelProperty(index = 2)
    private Date date;
}

3. controller 方法参数定义

支持 List<T>ReadRows<T> 两种类型的参数,在方法参数上添加 @ExcelParam 注解即可。

@PostMapping("/list/obj")
public List<DemoData> listObj(@ExcelParam List<DemoData> list){
    return list;
}
@PostMapping("/list/rows")
public ReadRows<DemoData> readRows(@ExcelParam(value = "file") ReadRows<DemoData> readRows){
    return readRows;
}

@ExcelParam 注解用于指定一些参数信息,类似于 @RequestParam 参数,定义如下。

public @interface ExcelParam {

    // 字段名称
    String value() default "file";

    // 是否必须
    boolean required() default true;
}

ReadRows 包含了一些关于行列的附加信息,例如解析出的对象对应哪一行数据、对象字段对应哪一列数据。定义如下:

public class ReadRows<T> {

    // 头信息元数据,包括列信息
    private ExcelReadHeadProperty excelReadHeadProperty;

    // 行信息
    private List<ReadRow<T>> rows;
}

public class ReadRow<T> {

    // 行索引,从 0 开始
    private final Integer rowIndex;

    // 行数据
    private final T data;
}  

导出

将 controller 方法返回值定义为 List<T> 类型,然后添加 @ExcelResponse 注解即可。

@ExcelResponse
@GetMapping("/list/download")
public List<DemoData> downloadList() {
        return Arrays.asList(new DemoData(1, "hello", new Date()), new DemoData(2, "excel", new Date()));
}

@ExcelResponse 注解用于定义一些导出的元数据,定义如下:

public @interface ExcelResponse {

    // 文件名称,不包含后缀
    String fileName() default "default";

    // sheet 名称
    String sheetName() default "Sheet1";
}

参数校验

参数校验是 Excel 导入常用的功能,看到其他人写过类似的项目,但是对参数校验的支持不是很友好,这里提供了更友好的校验功能,如 spring boot 原生校验般丝滑。

1. 开启校验

List<T>ReadRows<T> 类型的 controller 方法参数上添加 @Validated@Valid 注解即可。示例如下:

@PostMapping("/list/obj")
public List<DemoData> listObj(@ExcelParam @Validated List<DemoData> list){
        return list;
}

2. 定义校验规则

有两种方式定义校验规则。

2.1 JSR 303 规范校验

通过 JSR 303 规范定义的校验注解配置校验规则,需要引入 spring-boot-starter-validation

这是默认的校验方式,可通过设置环境变量 easyexcel.validator.default.enable=false 关闭。

示例如下:


@Data
public class DemoData {

    @NotNull(message = "数值不能为空")
    private Integer integer;

    @NotBlank(message = "字符串不能为空")
    private String string;

    private Date date;
}

还可以对整个对象校验。


@Data
@DemoDataValid
public class DemoData {

    private Integer integer;

    private String string;

    private Date date;
}

@Documented
@Target({TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = {DemoDataValid.DemoDataValidator.class})
public @interface DemoDataValid {

    String message() default "{com.zzuhkp.easyexcel.validator.DemoDataValid.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class DemoDataValidator implements ConstraintValidator<DemoDataValid, DemoData> {

        @Override
        public boolean isValid(DemoData value, ConstraintValidatorContext context) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("测试对象校验").addConstraintViolation();
            return false;
        }
    }

}

2.2 ExcelValidator 接口校验

JSR 303 规范只能校验单个对象或者字段,如果想要对导入所有对象进行校验可以使用框架定义的 ExcelValidator 接口,实现接口,并将实现类定义为 bean 即可,接口定义如下。

public interface ExcelValidator<T> {

    // 参数校验
    ExcelValidErrors validate(ReadRows<T> readRows);
}

ExcelValidErrors 作为校验的结果,包含了多个错误信息。

public class ExcelValidErrors {

    private final List<ExcelValidObjectError> errors;
}

错误信息又可以分为行错误信息与单元格错误信息,分别对应对象错误信息和字段错误信息。

行错误信息使用 ExcelValidObjectError 接口表示,接口定义如下:

public interface ExcelValidObjectError {

    // 获取行号,从 1 开始
    Integer getRow();

    // 获取错误消息
    String getMessage();
}

单元格错误信息使用 ExcelValidFieldError 表示,接口定义如下:

public interface ExcelValidFieldError extends ExcelValidObjectError {

    // 获取列,从 1 开始
    Integer getColumn();
}

如果默认实现不满足要求可自行提供实现。

例如,如果想校验上述导入示例中的 integer 列的值不能重复,可以使用如下的代码。

@Component
public class CustomExcelValidator implements ExcelValidator<DemoData> {
    @Override
    public ExcelValidErrors validate(ReadRows<DemoData> readRows) {
        ExcelValidErrors errors = new ExcelValidErrors();

        Map<Integer, List<ReadRow<DemoData>>> group = readRows.getRows().stream()
                .collect(Collectors.groupingBy(item -> item.getData().getInteger()));

        for (Map.Entry<Integer, List<ReadRow<DemoData>>> entry : group.entrySet()) {
            if (entry.getValue().size() > 1) {
                for (ReadRow<DemoData> readRow : entry.getValue()) {
                    errors.addError(new DefaultExcelObjectError(readRow.getRowIndex() + 1, "参数重复"));
                }
            }
        }
        return errors;
    }
}

3. 校验结果接收

校验结果同样有两种方式接收。

3.1 异常捕获接收

默认情况下,添加 @Validated@Valid 注解开启校验功能后,框架会将校验结果封装为 ExcelValidException 异常,可以使用 ControllerAdvice 进行全局异常捕获获取校验结果。

@RestControllerAdvice
public class GlobalExceptionControllerAdvice {

    @ExceptionHandler(Exception.class)
    public String handleException(ExcelValidException e) {
        ExcelValidErrors errors = e.getErrors();
        return JSON.toJSONString(errors);
    }
}

3.2 ExcelValidErrors 类型参数接收

如果不想通过异常捕获的方式接收校验结果,可以将 ExcelValidErrors 类型的参数定义到 @ExcelParam 参数后。示例代码如下:

@PostMapping("/list/obj")
public List<DemoData> listObj(@ExcelParam @Validated List<DemoData> list, ExcelValidErrors errors) {
    if (errors.hasErrors()) {
        String messages = errors.getAllErrors().stream().map(ExcelValidObjectError::getMessage).collect(Collectors.joining(" | "));
        throw new RuntimeException("发现异常:" + messages);
    }
    return list;
}

其他说明

如果你在使用过程中遇到任何问题,可以随时提 issue 反映。

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

基于 easyexcel 的 spring-boot-starter,简化了 Web 环境下 Excel 的导入与导出操作。 展开 收起
Java
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/zzuhkp/easyexcel-spring-boot-starter.git
git@gitee.com:zzuhkp/easyexcel-spring-boot-starter.git
zzuhkp
easyexcel-spring-boot-starter
easyexcel-spring-boot-starter
master

搜索帮助