2.导入依赖(在pom中导入)
< 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>
< 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 ;
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.创建一个监听器继承AnalysisEventListener
package com. huyi. easyexcel. listenter ;
import java. util. Map ;
import com. alibaba. excel. context. AnalysisContext ;
import com. alibaba. excel. event. AnalysisEventListener ;
import com. huyi. easyexcel. pojo. User ;
public class ReadListenter extends AnalysisEventListener < User > {
public void invokeHeadMap ( Map < Integer , String > headMap, AnalysisContext context) {
System . err. println ( headMap) ;
}
@Override
public void invoke ( User data, AnalysisContext context) {
System . err. println ( data. getUserId ( ) + "" + data. getUserName ( ) + "" + data. getPassWord ( ) + "" + data. getEmail ( ) ) ;
}
@Override
public void doAfterAllAnalysed ( AnalysisContext context) {
}
}
5.在项目的test中测试
package com. huyi. easyexcel ;
import org. junit. jupiter. api. Test ;
import org. springframework. boot. test. context. SpringBootTest ;
import com. alibaba. excel. EasyExcel ;
import com. huyi. easyexcel. listenter. ReadListenter ;
import com. huyi. easyexcel. pojo. User ;
@SpringBootTest
class EasyexcelApplicationTests {
@Test
void testRead ( ) {
String fileName = "E:\\test.xlsx" ;
EasyExcel . read ( fileName, User . class , new ReadListenter ( ) ) . sheet ( ) . doRead ( ) ;
}
}
6.运行结果如下