添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<!-- 使用 xlsx 格式 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
代码实现
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args){
String[] header = {“编码”, “姓名”, “年龄”};
User user = new User(1, “小米”, 18);
User userNew = new User(2, “小明”, 19);
List data = new ArrayList<>();
list.add(user);
list.add(userNew);
export(data, header);
}
private static void export(List<User> data, String[] header) {
String[] fieldNames = fieldName(User.class);
Workbook wb = new HSSFWorkbook();
int rowSize = 0;
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(rowSize);
for (int i = 0; i < header.length; i++) {
row.createCell(i).setCellValue(header[i]);
}
try {
for (int x = 0; x < data.size(); x++) {
rowSize = 1;
Row rowNew = sheet.createRow(rowSize + x);
for (int i = 0; i < header.length; i++) {
User user = data.get(x);
for (int i1 = 0; i1 < fieldNames.length; i1++) {
String methodName = "get" + fieldNames[i].substring(0, 1).toUpperCase() + fieldNames[i].substring(1);//获取属性的get方法名
Method method = user.getClass().getMethod(methodName);
Object invoke = method1.invoke(user);//获取属性值
rowNew.createCell(i).setCellValue(invoke.toString());
}
}
}
} catch (Exception e) {
}
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream("aaa.xls");
wb.write(outputStream);
} catch (Exception e) {
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (Exception e) {
}
try{
if(wb != null){
wb.close();
}
} catch (Exception e){
}
}
}
private static String[] fieldName(Class clazz) {
Field[] declaredFields = clazz.getDeclaredFields();
String[] fieldNames = new String[declaredFields.length];
for (int i = 0; i < declaredFields.length; i++) {
fieldNames[i] = declaredFields[i].getName(); //通过反射获取属性名
}
return fieldNames;
}
}