1.设计注解
注解使用到 FIELD 上
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel{
String name;
}
2,设计javaBean
public class OutDataBean{
@Excel(name="No")
private String no;
@Excel(name="before")
private String bef;
@Excel(name="after")
private String aft;
........//getter setter
}
3.设计注解类的实现
public class ExcelUtil<T> {
Class<T> clazz;
public ExcelUtil(Class<T> clazz){
this.clazz = clazz;
}
// convert java bean list to excel.xlsx
public boolean exportExcel(String file,Sthing sheetNm,List<T> datas) throws Exception {
XSSFWorkBook xfWb = new XSSFWorkBook();
XSSFSheet createSheet = xfWb.createSheet(sheetNm);
int rowIndex = 0;
XSSFRow createRow = createSheet.createRow(rowIndex);
//
Map<Integer,Field> fieldsMap = new HashMap<>();
List<Field> allFields = getClazzField(clazz,null);
int colIndex = 0 ;
// 写入header内容,并设置cell格式
for(Field field : allFields){
// 只处理有Excel注解的对象
if(!field.isAnnotationPresent(Excel.class)) continue;
field.setAccessible(true);
fieldsMap.put(colIndex,field);
XSSFCell createCell createRow.createCell(colIndex);
createCell.setCellValue(field.getName());
Map<String,CellStyle> createStyle = createStyles(xfWb);
createCell.setCellStyle(createStyle.get("green_center"));
colIndex +=1;
}
rowIndex +=1;
// 写入明细行数据
for(T t : datas){
XSSFRow dataRow = createSheet.createRow(rowIndex );
rowIndex +=1;
for(int j=0;j<fieldsMap.size();j++){
XSSFCell dataCell = dataRow.createCell(j);
Field field = fieldsMap.get(j);
dataCell.setCellValue(null == field.get(t) ? "" : field.get(t).toString());
}
}
//write file
try(FileOutputStream fos = new FileOutputStream()){
xfWb.write(fso);
} catch (Exception e){ return false; }
return true;
}
// get all fields
private List<Field> getClazzField(Class<?> clazz,List<Field> fields){
if(Objects.isNull(fields)) fiedls = new ArrayList<>();
Field[] fieldArr = clazz.getDeclaredFields();
if(!Objects.isNull(fieldArr)) fields.addAll(Arrays.asList(fieldArr));
//
if(Objects.nonNull(clazz.getSuperclass) && !clazz.getSuperclass().equals(Objects.class))
getClazzField(clazz.getSuperclass(),fields);
return fields;
}
// style
private Map<String,CellStyle> createStyles(Workbook wb){
Map<String,CellStyle> styles = new HashMap<>();
//
Font f =wb.createFont();
f.setFontName("MS UI Gothic");
//
CellStyle style;
style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.LiGHT_GREEN.getIndex());
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setFont(f);
styles.put("green_center",style);
//add other style ......
return styles;
}
}
5.调用
ExcelUtil<OutDataBean> util = new ExcelUtil<>(OutDataBean.class);
//
List<OutDataBean> datas = new ArrayList<>();
for(int i=0;i<10;i++){
OutDataBean b=new OutDataBean();
b.setNo(Sting.valueOf(i));
b.setBef("Before" + i);
b.setAft("After"+(i+100));
datas.add(b);
}
try{
util.exportExcel("/test.xlsx","test",datas);
}catch(Exception e){
e.printStackTrance();
}