导出工具类
package com.lovefly.util;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.List;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import com.lovefly.service.api.excel.Excelable;
public class ExcelUtil<T extends Excelable> {
private WritableWorkbook book ;
private WritableSheet sheet;
private int rowIndex = 0;
List<String> attrs;
List<T> poList;
Class<T> clas;
public ExcelUtil(OutputStream out,String name,List<String> attrs,List<T> poList,Class<T> c) throws IOException {
book = Workbook.createWorkbook(out);
sheet = book.createSheet(name, 0);
this.attrs = attrs;
this.poList = poList;
clas = c;
}
private void writeBody() throws Exception {
Label label = null;
for(int i=0;i<poList.size();i++){
for(int j=0;j<attrs.size();j++){
Field field = clas.getDeclaredField(attrs.get(j));
field.setAccessible(true);
label = new Label(j,rowIndex,field.get(poList.get(i)).toString());
sheet.addCell(label);
}
rowIndex++;
}
}
private void writeTitle() throws Exception{
Label label = null;
for(int i=0;i<attrs.size();i++){
label = new Label(i,rowIndex,clas.newInstance().getAttrTitleMapping().get(attrs.get(i)));
sheet.addCell(label);
}
rowIndex++;
}
public void writeClose(){
try {
writeTitle();
writeBody();
book.write();
book.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这个工具类,跟你是什么类型是没关系的
for(int j=0;j<attrs.size();j++){
Field field = clas.getDeclaredField(attrs.get(j));
field.setAccessible(true);
label = new Label(j,rowIndex,field.get(poList.get(i)).toString());
sheet.addCell(label);
}
Field field = clas.getDeclaredField(attrs.get(j)); 根据你传入的名称获得这个class的成员变量
比如我们传入了student 类 有id,age,name 三个属性
你的attrs 集合里面应该存入了attrs[0]="id",attrs[1]="age",attrs[2]="name"
假如j=0:现在的field=student.id;获取到了student.id成员变量;
field.get(poList.get(i))---获取class的成员变量的值
你传入的是student 类的集合,所以你可以获取到第一个student 的id的值
如果是int类型的值你做.tostring(),肯定不行的啊,int 是没有tostring()方法的