- /***
- * 生成csv文件
- *
- * @param context
- * @param list
- * 对象集合
- * @param csvName
- * 对应的文件名称
- * @param propertyArray
- * 属性字符串,逗号分割
- */
- public static void writeCsvFile(Context context, List list, String csvName,
- String folder, String propertyArray) {
- if (list == null || list.isEmpty())
- return;
- // sdcard/com/cela/目录下
- String path = DataUtils.getCsvFilePath(folder);
- File file = new File(path);
- if (!file.exists()) {
- file.mkdirs();
- }
- path += csvName;
- // 判断文件是否存在,如果存在则取出原有数据
- List<String[]> originalList = null;
- try {
- File f = new File(path);
- if (f.exists()) {
- originalList = new ArrayList<String[]>();
- CSVReader reader = new CSVReader(new FileReader(path), ',');
- originalList.addAll(reader.readAll());
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- OutputStreamWriter fw = null;
- CSVWriter csv = null;
- // 通过反射获取list里面的值
- try {
- fw = new OutputStreamWriter(new FileOutputStream(path), "UTF-8");
- csv = new CSVWriter(fw, ',');
- final int size = list.size();
- // 写入原有数据
- if (originalList != null && !originalList.isEmpty()) {
- final int len = originalList.size();
- for (int i = 0; i < len; i++) {
- csv.writeNext(originalList.get(i));
- }
- }
- // 开始写入对象
- for (int i = 0; i < size; i++) {
- Object obj = list.get(i);
- Class cla = obj.getClass();
- String[] propertys = propertyArray.split(",");
- String[] values = new String[propertys.length];
- for (int j = 0; j < propertys.length; j++) {
- Field field = cla.getDeclaredField(propertys[j]);
- String fname = field.getName();
- String strLitter = fname.substring(0, 1).toUpperCase();
- String getName = "get" + strLitter + fname.substring(1);
- String setName = "set" + strLitter + fname.substring(1);
- Method getmethod = cla.getMethod(getName, new Class[] {});
- cla.getMethod(setName, new Class[] { field.getType() });
- Object value = getmethod.invoke(obj, new Object[] {});
- if(value!=null){
- values[j] = (String) value.toString();
- }else{
- values[j] = "";
- }
- }
- csv.writeNext(values);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (csv != null) {
- try {
- csv.flush();
- csv.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }