依赖jar包(可以在apache官网下载 评论也放了下载连接)
方法本体
/**
* 将List集合内容写到excel表中
* @param list list对象
* @param xlsPath 文件要写到的位置
* @param xlsName excel sheet表名
* @param titles 标题栏
*/
public static void poiImport(List list, String xlsPath, String xlsName, String... titles) {
//先创建一个xls文件 workBook对象 代表excel文件
Workbook workbook = new HSSFWorkbook();
//创建一个sheet表
Sheet sheet = workbook.createSheet(xlsName);
//先打印标题栏
int rowIndex = 0;
Row row = sheet.createRow(rowIndex++);
for (int i = 0; i < titles.length; i++) {
row.createCell(i).setCellValue(titles[i]);
}
//打印list内容
for (int i = 0; i < list.size(); i++) {
//创建行
Row row1 = sheet.createRow(rowIndex);
//反射得到Class
Class clazz = list.get(0).getClass();
//反射得到所有属性
Field[] fields = clazz.getDeclaredFields();
int cellIndex = 0;
for (int j = 0; j < fields.length; j++) {
try {
//得到属性
Field field = fields[j];
//打开私有访问权限
field.setAccessible(true);
//获得属性值
Object value = field.get(list.get(i));
//创建列
row1.createCell(cellIndex++).setCellValue(value + "");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
rowIndex++;
break;
}
//将内容输出
try {
workbook.write(new FileOutputStream(new File(xlsPath)));
} catch (IOException e) {
e.printStackTrace();
}
}
测试类Student(属性 构造器 和重写了toString方法)
public class Student {
private String name;
private int age;
private String gender;
private float score;
private String school;
public Student() {
}
public Student(String name, int age, String gender, float score, String school) {
this.name = name;
this.age = age;
this.gender = gender;
this.score = score;
this.school = school;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", gender=" + gender +
", score=" + score +
", school='" + school +'}';
}
}
测试代码
public static void main(String[] args) {
//创建list对象
List<Student> list = new ArrayList<>();
//循环常见50个Student对象
for (int i = 0; i < 50; i++) {
list.add(new Student(("张大帅" + i), (i + 1), "MAN", 100, ("中北大学" + i));
}
//调用方法
poiImport(list, "E:\\desk\\student.xls", "学生信息表", "姓名", "年龄", "性别", "成绩", "学校");
}
excel文件内容