导入easyexcel依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.1.6</version> </dependency>
实体类:
package com.zhang.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.metadata.BaseRowModel;
import com.baomidou.mybatisplus.annotation.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.apache.poi.ss.usermodel.CellStyle;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
/**
* @author Ryan
* @since 2022-01-09
*/
@Data
@ColumnWidth(25)
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("animal")
@ApiModel(value="Animal对象", description="")
public class Animal implements Serializable {
private static final long serialVersionUID=1L;
@ExcelIgnore
@ApiModelProperty(value = "主键id")
@TableId(value = "id", type = IdType.UUID)
private String id;
@ExcelProperty(value = "姓名",index = 0)
@Pattern(regexp = "^[0-9]*$",message = "只能输入1-9的数字")
@NotBlank(message = "name不能为空")
@ApiModelProperty(value = "名称")
private String name;
@ExcelProperty(value = "年龄",index = 2)
@NotNull(message = "年龄不能为空")
@ApiModelProperty(value = "年龄")
private Integer age;
@TableLogic
@ExcelIgnore
@ApiModelProperty(value = "删除状态(0-正常,1-已删除)")
private Integer delFlag;
@ExcelProperty(value = "爱好",index = 1)
@ApiModelProperty(value = "爱好")
private String hobby;
@ExcelProperty(value = "创建时间",index = 3)
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@ExcelProperty(value = "更新时间",index = 4)
@TableField(fill = FieldFill.UPDATE)
private Date updateTime;
}
controller方法:
/**
* 导出信息到Excel
*/
@GetMapping(value = "/exportFile")
public Result<?> file() {
ExcelWriter excelWriter = null;
//文件名
String fileName="test.xlsx";
List<Animal> list = animalService.list();
try {
// 定义一个全局的URL,作为文件的输出路径
excelWriter = EasyExcel.write(URL+fileName, Animal.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
excelWriter.write(list, writeSheet);
} finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
return Result.OK();
}
数据顺利导出~