1.Maven环境
使用alibaba的easyexcel,操作简单,代码不冗余
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
2.完整代码实现
MyUser实体类: @ExcelProperty()就是用来设置表头的, 也可以这样写:@ExcelProperty(value="名称",index=索引), 此外@ExcelProperty()还有很多配置各种类型的表头, 详情可以参考EasyExcel官方文档
package com.bjfu.entity;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.sql.rowset.BaseRowSet;
import java.io.Serializable;
import java.util.Date;
/**
* @author 旺旺米雪饼
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class MyUser extends BaseRowSet implements Serializable {
private static final long serialVersionUID= 5155541187667989703L;
@ExcelProperty(value = {"userId"}, index = 0)
private Long userId;
@ExcelProperty(value = {"userName"}, index = 1)
private String userName;
@ExcelProperty(value = {"password"}, index = 2)
private String password;
/**
* 是否被删除。0是未删除,1是删除
*/
@ExcelProperty(value = {"isDeleted"}, index = 3)
private Integer isDeleted;
@ExcelProperty(value = {"createTime"}, index = 4)
private Date createTime;
@ExcelProperty(value = {"updateTime"}, index = 5)
private Date updateTime;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
@Override
public String getPassword() {
return password;
}
@Override
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public Integer getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Integer isDeleted) {
this.isDeleted = isDeleted;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
写一个TestFileUtil工具类:
public class TestFileUtil {
//因为这个简单的导入导出没有用到什么别的功能,我这里就只写了一个路径
public static String getPath() {
return "D:/code/";
}
}
UserController中添加下面的方法:
@PostMapping("/ExportExcel")
public void ExportExcel() {
String fileName = TestFileUtil.getPath() + "User" + System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为用户表 然后文件流会自动关闭
EasyExcel.write(fileName, MyUser.class).sheet("用户表").doWrite(data());
}
Service层添加业务逻辑:
public List<MyUser> select(){
List<MyUser> list=new ArrayList<>();
list.add(0,myUserMapper.selectByPrimaryKey(1L));
return list;
}
这里我直接把查询写死了,查询id为1的用户并输出到excel文件中。
在swagger-ui界面中可以看到exceptexcel接口,我们来测试一下。在文件夹下生成了xlsx文件