一 导入对应的excel jar包
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
二 动态创建excel
public class CreateExcelUtil {
/**
* 将list集合转成Excel文件
* @param list 对象集合
* @param path 输出路径
* @return 返回文件路径
*/
public StringcreateExcel(List list, String path, String fileName)throws Exception {
String result ="";
if (list.size()==0||list==null) {
result ="没有对象信息";
} else {
Object o = list.get(0);
Class clazz = o.getClass();
String className = clazz.getSimpleName();
Field[] fields=clazz.getDeclaredFields(); //这里通过反射获取字段数组
File folder =new File(path);
if (!folder.exists()) {
folder.mkdirs();
}
//String fileName = FORMATTER.format(new Date());
String name = fileName.concat(".xls");
WritableWorkbook book =null;
File file =null;
try {
file =new File(path.concat(File.separator).concat(name));
book = Workbook.createWorkbook(file); //创建xls文件
int i =0; //列
int j =0; //行
// for(Field f:fields){循环列第一种方式创建 不能创建sheet
// j = 0;
// Label label = new Label(i, j,f.getName()); //这里把字段名称写入excel第一行中
// sheet.addCell(label);
// j = 1;
// for(Object obj:list){
// Object temp = getFieldValueByName(f.getName(),obj);
// String strTemp = "";
// if(temp!=null){
// strTemp = temp.toString();
// }
// sheet.addCell(new Label(i,j,strTemp)); //把每个对象此字段的属性写入这一列excel中
// j++;
// }
// i++;
// }
//i 代表列 j 代表行
int k =0;
WritableSheet sheet =null;
for (Object obj:list) {//循环行并且动态创建sheet第二种方式创建
if (j %60000 ==0) {
k++;
j=0;
sheet = book.createSheet(className, k);
sheet.setName(fileName);
for (Field f : fields) {
Label label =new Label(i, j, f.getName()); //这里把字段名称写入excel第一行中
sheet.addCell(label);
i++;
}
j=1;
i=0;
}
for (Field f : fields) {
Object temp =getFieldValueByName(f.getName(), obj);
String strTemp ="";
if (temp !=null) {
strTemp = temp.toString();
}
sheet.addCell(new Label(i, j, strTemp)); //把每个对象此字段的属性写入这一列excel中
i++;
}
i=0;
j++;
}
book.write();
result = file.getPath();
} catch (Exception e) {
result ="SystemException";
e.printStackTrace();
} finally {
if (book != null ){
try {
book.close();
} catch (WriteException e) {
result ="WriteException";
e.printStackTrace();
} catch (IOException e) {
result ="IOException";
e.printStackTrace();
}
}
}
}
return result; //最后输出文件路径
}
/**
* 获取属性值
* @param fieldName 字段名称
* @param o 对象
* @return Object
*/
private static ObjectgetFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter ="get" + firstLetter + fieldName.substring(1); //获取方法名
Method method = o.getClass().getMethod(getter, new Class[] {}); //获取方法对象
Object value = method.invoke(o, new Object[] {}); //用invoke调用此对象的get字段方法
return value; //返回值
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
以上提供2种方式创建 第一种局限性很大 主要是因为数据量大的情况下不能创建sheet
在学习的过程中希望大家互相关注托提意见 hhh 感谢您的浏览!!!