工具类uml图:
使用案例:
/*
* 说明:
* house为list集合,"e:\\test\\house.txt"为要保存地的路径。
*/
ListSaveAsExcelFormat.enterWay(houses, "e:\\test\\house.txt");
产生的house.txt文件是按照excel格式生成数据的,所以选中里面的所有文件,复制到excel表格中,即可生成excel表格。
ListSaveAsExcelFormat类源码:
public class ListSaveAsExcelFormat {
public static void enterWay(List list, String dir) {
ListToArray la = new ListToArray();
String[][] arr = la.listToArrayWay(list);
try {
WriteArrayToTxt.writeToTxt("e:\\test\\house.txt", arr);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("存放路径有问题");
e.printStackTrace();
}
}
}
ListToArray源码:
public class ListToArray {
/**
* 获取对象属性,返回一个字符串数组
*
* @param o 对象
* @return String[] 字符串数组
*/
private String[] getFiledName(Object o) {
try {
Field[] fields = o.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
fieldNames[i] = fields[i].getName();
}
return fieldNames;
} catch (SecurityException e) {
e.printStackTrace();
System.out.println(e.toString());
}
return null;
}
/**
* 使用反射根据属性名称获取t属性的get方法
*
* @param fieldName 属性名称
* @param o 操作对象
* @return List<Method> get方法
*/
private List<Method> getGetField(String[] fieldNames, Object o) {
List<Method> methods=new ArrayList<Method>();
for (String fieldName : fieldNames) {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = null;
try {
method = o.getClass().getMethod(getter, new Class[] {});
} catch (NoSuchMethodException e) {
System.out.println("属性不存在");
continue;
}
//Object value = method.invoke(o, new Object[] {});
methods.add(method);
}
return methods;
}
/**
* 将list集合转换为二维string数组
*
* @param list 要转换的集合
* @return String[][] 返回的sting数组
*/
public String[][] listToArrayWay(List list) {
Object o=list.get(0);
String[] filedNames = getFiledName(o);
int filedNum=filedNames.length;
int listSize=list.size();
List<Method> methods=getGetField(filedNames, o);
String[][] arrs=new String[listSize][filedNum];
int i=0;
for (Object object : list) {
int j=0;
for (Method method : methods) {
Object value=null;
try {
value = method.invoke(object, new Object[] {});
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("属性不存在"+e);
}
arrs[i][j]=(String) value;
j++;
}
i++;
}
return arrs;
}
}
WriteArrayToTxt源码:
public class WriteArrayToTxt {
public static void writeToTxt(String fileDir, String[][] strss) throws Exception {
FileWriter fileWriter = new FileWriter(fileDir);
for (String[] strs : strss) {
for (String str : strs) {
fileWriter.write(str + "\t");
}
fileWriter.write("\r\n");
}
// 关闭写入文件流
fileWriter.flush();
fileWriter.close();
}
}