前阵子有朋友问我java将excel转成文档的方法(用此方法需要引入jxl包),而最近公司刚好有个需求需要将数据转成excel文档。所以我就写了一个工具类,将数据对象转成excel文档。考虑到可能要传入不同类型的对象集合。为了能配合我那个朋友使用,也为了工具类更具有复用性,excel的第一行信息通过反射获取对象的属性名称来写入。
首先要做一个 通过字段名称获取属性值 的方法:
/**
* 获取属性值
* @param fieldName 字段名称
* @param o 对象
* @return Object
*/
private static Object getFieldValueByName(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;
}
}
接下来我们要写一个将list集合转成excel文件的方法
/**
* 将list集合转成Excel文件
* @param list 对象集合
* @param path 输出路径
* @return 返回文件路径
*/
public static String createExcel(List<? extends Object> list,String path){
String result = "";
if(list.size()==0||list==null){
result = "没有对象信息";
}else{
Object o = list.get(0);
Class<? extends Object> 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文件
WritableSheet sheet = book.createSheet(className,0);
int i = 0; //列
int j = 0; //行
for(Field f:fields){
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++;
}
book.write();
result = file.getPath();
} catch (Exception e) {
// TODO Auto-generated catch block
result = "SystemException";
e.printStackTrace();
}finally{
fileName = null;
name = null;
folder = null;
file = null;
if(book!=null){
try {
book.close();
} catch (WriteException e) {
// TODO Auto-generated catch block
result = "WriteException";
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
result = "IOException";
e.printStackTrace();
}
}
}
}
return result;