@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelAnnotation {
int order();
}
public class Student {
@ExcelAnnotation(order = 1)
private String id;
@ExcelAnnotation(order = 2)
private String name;
@ExcelAnnotation(order = 3)
private int age;
@ExcelAnnotation(order = 4)
private Date entranceTime = new Date();
@ExcelAnnotation(order = 5)
private Boolean readind;
..............get..set必须自动生成
}
SXSSFUtil
public class SXSSFUtil {
public static void saveListAsXlsx(List objectList, String[] headers, String fileName, String sheetName) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
/**
* SXSSFWorkbook(int rowAccessWindowSize)
* rowAccessWindowSize 代表指定的内存中缓存记录数,默认为100
* 比如内存中限制行数为100,当行号到达101时,行号为0的记录刷新到硬盘并从内存中删除,
* 当行号到达102时,行号为1的记录刷新到硬盘,并从内存中删除,以此类推。
*/
SXSSFWorkbook wb = new SXSSFWorkbook(100);
SXSSFSheet sheet = wb.createSheet(sheetName);
SXSSFRow head = sheet.createRow(0);
int cloumn = 0;
for (String title : headers) {
SXSSFCell cell = head.createCell(cloumn++);
cell.setCellValue(title);
}
int rowNo = 1;
// row
for (Object object : objectList) {
SXSSFRow row = sheet.createRow(rowNo++);
// cloumn
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(ExcelAnnotation.class)) {
ExcelAnnotation excelAnnotation = field.getAnnotation(ExcelAnnotation.class);
int order = excelAnnotation.order();
SXSSFCell cell = row.createCell(order - 1);
String fieldName = field.getName();
Method method = object.getClass().getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));
Object valueObj = method.invoke(object);
if (valueObj == null) {
cell.setCellValue("");
} else {
if (field.getType().equals(Date.class)) {
String value = DateUtil.format_yyyyMMddHHmmss((Date) valueObj);
cell.setCellValue(value);
} else {
cell.setCellValue(valueObj.toString());
}
}
}
}
}
FileOutputStream fos = new FileOutputStream(fileName);
wb.write(fos);
fos.close();
// 处理工作表在磁盘上产生的临时文件
wb.dispose();
}
}
测试:
public class SXSSFUtilTest {
public static void main(String[] args) {
String[] headers = {"学号","姓名","年龄","入学日期","是否在读"};
List<Student> studentList = new ArrayList<>();
for (int i=0;i<10;i++){
Student student = new Student(""+i,"学生"+i,i*2,true);
studentList.add(student);
}
try {
SXSSFUtil.saveListAsXlsx(studentList,headers,"D:/学生表.xlsx","sheet1");
} catch (Exception e) {
e.printStackTrace();
}
}
}