用excel4j读写excel表格十分简洁省事
导入excel4j依赖
<dependency>
<groupId>com.github.crab2died</groupId>
<artifactId>Excel4J</artifactId>
<version>3.0.0-Alpha</version>
</dependency>
准备好excel表格文件和对应的实体类,注解是excel对应的值
package com.tac.excel.pojo;
import com.github.crab2died.annotation.ExcelField;
public class UserExcel {
@ExcelField(title = "编号")
private String id;
@ExcelField(title = "用户名")
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UserExcel(String id, String name) {
this.id = id;
this.name = name;
}
public UserExcel() {
}
}
读取
通过ExcelUtils.getInstance().readExcel2Object(文件路径,clazz);常用方法读取excel和csv,返回对象集合
package com.tac.test;
import com.github.crab2died.ExcelUtils;
import com.github.crab2died.exceptions.Excel4JException;
import com.tac.excel.pojo.UserExcel;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExcelTest {
public static void main(String[] args) throws Excel4JException, IOException, InvalidFormatException {
//读取
//通过ExcelUtils.getInstance().readExcel2Object(文件路径,clazz);常用方法读取excel和csv,返回对象集合
List<UserExcel> userExcels =
ExcelUtils.getInstance().readExcel2Objects("C:\\Users\\Administrator\\Desktop\\user.xls", UserExcel.class);
for (UserExcel user : userExcels) {
System.out.println(user.getId());
System.out.println(user.getName());
System.out.println("--------------------------");
}
}
}
写入同理,如果没有此文件会先生成一个,如果有此文件会覆盖
package com.tac.test;
import com.github.crab2died.ExcelUtils;
import com.github.crab2died.exceptions.Excel4JException;
import com.tac.excel.pojo.UserExcel;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExcelTest {
public static void main(String[] args) throws Excel4JException, IOException, InvalidFormatException {
//写入
ArrayList<UserExcel> list = new ArrayList<>();
list.add(new UserExcel("56","李四"));
ExcelUtils.getInstance().exportObjects2Excel(list,UserExcel.class,"C:\\Users\\Administrator\\Desktop\\user.xls");
}
}