SpringBoot集成Easyexcel-写入
作者:互联网
1.创建一个SpringBoot项目(SpringBoot生成)
2.导入依赖(在pom中导入)
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
3.创建一个实体类(User)
package com.huyi.easyexcel.pojo;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @HeadRowHeight(int):设置表头高度(与 @ContentRowHeight 相反)标记在类上
* @ColumnWidth(int):设置列宽标记在属性上
* @ExcelProperty("String") 是标题
* @ColumnWidth(value = 20) 宽度 value:宽度大小
* @ContentRowHeight(int):设置 row 高度,不包含表头标记在 类上
*/
public class User {
@ExcelProperty(value ="用户ID",index = 0)
private Long userId;
@ExcelProperty(value ="用户名",index = 1)
private String userName;
@ExcelProperty(value ="用户密码",index = 2)
private String passWord;
@ExcelProperty(value ="用户邮箱",index = 3)
private String email;
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;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User(Long userId, String userName, String passWord, String email) {
this.userId = userId;
this.userName = userName;
this.passWord = passWord;
this.email = email;
}
public User() {
}
}
4.在项目的test中测试
package com.huyi.easyexcel;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import com.alibaba.excel.EasyExcel;
import com.huyi.easyexcel.pojo.User;
@SpringBootTest
class EasyexcelApplicationTests {
@Test
void contextLoads() {
// 文件的下载路径(或写入路径)
String fileName = "E:\\test.xlsx";
//模拟写入数据
List<User> userList = new ArrayList<User>();
//循环写入数据
for(int i=0;i<18;i++) {
Long userId = (long)i+1;
User user = new User();
user.setUserId(userId);
user.setUserName("name"+userId);
user.setPassWord("password"+userId);
user.setEmail("xxx@163.com");
userList.add(user);
}
for(User user:userList) {
System.err.println(user.getUserName());
}
/**
* .write(fileName, ExcelData.class) fileName 是写入路径, ExcelData.class 是接收实体类
* .sheet 是sheet表的名称
* .doWrite 是要写入的数据List
*/
EasyExcel.write(fileName,User.class).sheet("用户表").doWrite(userList);
}
}
- 注意:文件如果打开的话运行会报错
5.运行结果如下
标签:userName,SpringBoot,userId,Easyexcel,写入,email,import,public,String 来源: https://www.cnblogs.com/Huyi-1208/p/16403803.html