자바 작업 csv 문서 유 니 버 설 도구 클래스

package cn.com.test.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
*      
* @author:  Rodge
* @time:    2017 12 25    9:39:18
* @version: V1.0.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CSVField {

	/**
     * CSV    
     */
    public String name() default "";
       
}

 
csv 도구 클래스
 
package cn.com.javatest.utils;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.util.ReflectionUtils;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

import cn.com.javatest.annotation.CSVField;

/**
 * CSV   
 * 
 * @author:  Rodge
 * @time:    2017 12 25    10:02:08
 * @version: V1.0.0
 */
public final class CSVUtils {

	/**      **/  
    private static final Logger LOGGER = Logger.getLogger(CSVUtils.class); 
    
    /**     **/ 
    private static final String TEMP_PATH = "temp.csv";
  
    /**          **/  
    private CSVUtils() { }
    
    /** 
     *   CSV   
     * 
     * @param filePath       ,  :D:/temp/test.csv 
     * @param beans        
     */  
    public static  void createCSVFile(String filePath, List beans) {    
        CsvWriter writer = null;  
        try {  
            //         
        	createDir(filePath);  
            //       
            writer = new CsvWriter(filePath, ',', Charset.forName("GBK"));           
            //       
            List contents = getStringArrayFromBean(beans);   
            //       
            for (String[] each : contents) {    
                writer.writeRecord(each, true);    
            }    
        } catch (Exception e) {  
            LOGGER.error("  CSV    ", e);  
        } finally {  
            if (writer != null) {  
                writer.close();            
            }  
        }  
    }
    
    /** 
     *   CSV   
     * 
     * @param request      
     * @param response      
     * @param beans        
     */  
    public static  void exportCSVFile(HttpServletRequest request, HttpServletResponse response, List beans) {    
    	String path = request.getServletContext().getRealPath("/");
    	try (FileInputStream input = new FileInputStream(createFile(path + TEMP_PATH))) {  
    		//       
    		CsvWriter writer = new CsvWriter(path + TEMP_PATH, ',', Charset.forName("GBK"));           
    		//       
    		List contents = getStringArrayFromBean(beans);   
    		//       
    		for (String[] each : contents) {    
    			writer.writeRecord(each, true);    
    		}    
    		writer.close();
    		//     
    		ServletOutputStream output = response.getOutputStream();
    		//             
            String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            response.setContentType("application/csv;charset=UTF-8");  
    		response.setHeader("Access-Control-Allow-Origin", "*");
    		response.setHeader("Access-Control-Expose-Headers", "*");
    		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".csv");
    		int len = -1;
    		byte[] b = new byte[1024 * 1024];
    		while((len = input.read(b)) != -1) {    
    			output.write(b, 0, len);
    		} 
    		output.close();
    	} catch (Exception e) {  
    		LOGGER.error("  CSV    ", e);  
    	} finally {  
    		deleteFile(path, TEMP_PATH);
    	}  
    }
    
    /** 
     *   CSV   
     * 
     * @param request      
     * @param response      
     * @param beans        
     * @param fileName      , :     
     */  
    public static  void exportCSVFile(HttpServletRequest request, HttpServletResponse response, List beans, String fileName) {    
    	String path = request.getServletContext().getRealPath("/");
    	try (FileInputStream input = new FileInputStream(createFile(path + TEMP_PATH))) {  
    		//       
    		CsvWriter writer = new CsvWriter(path + TEMP_PATH, ',', Charset.forName("GBK"));           
    		//       
    		List contents = getStringArrayFromBean(beans);   
    		//       
    		for (String[] each : contents) {    
    			writer.writeRecord(each, true);    
    		}    
    		writer.close();
    		//     
    		ServletOutputStream output = response.getOutputStream();
    		response.setContentType("application/csv;charset=UTF-8");  
    		response.setHeader("Access-Control-Allow-Origin", "*");
    		response.setHeader("Access-Control-Expose-Headers", "*");
    		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".csv");
    		int len = -1;
    		byte[] b = new byte[1024 * 1024];
    		while((len = input.read(b)) != -1) {    
    			output.write(b, 0, len);
    		} 
    		output.close();
    	} catch (Exception e) {  
    		LOGGER.error("  CSV    ", e);  
    	} finally {  
    		deleteFile(path, TEMP_PATH);
    	}  
    }
    
    /**
     *   CSV  
     * 
     * @param request     
     * @param response     
     * @param beans       
     */
    public static  void exportCSVTemplate(HttpServletRequest request, HttpServletResponse response, Class clazz) {
    	//             
    	String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    	exportCSVTemplate(request, response, clazz, fileName);
    }
    
    /**
     *   CSV  
     * 
     * @param request     
     * @param response     
     * @param beans       
     * @param fileName     
     */
    public static  void exportCSVTemplate(HttpServletRequest request, HttpServletResponse response, Class clazz, String fileName) {
    	String path = request.getServletContext().getRealPath("/");
    	try (FileInputStream input = new FileInputStream(createFile(path + TEMP_PATH))) {  
    		//       
    		CsvWriter writer = new CsvWriter(path + TEMP_PATH, ',', Charset.forName("GBK"));           
    		//             
    		Field[] declaredFields = clazz.getDeclaredFields();    
    		List annoFields = new ArrayList();     
    		for (Field field : declaredFields) {  
    			CSVField anno = field.getAnnotation(CSVField.class);    
    			if (anno != null) {   
    				annoFields.add(field);    
    			}  
    		}
    		//       ,       
    		String[] title = new String[annoFields.size()];       
    		for (int i = 0; i < annoFields.size(); i++) {    
    			title[i] = annoFields.get(i).getAnnotation(CSVField.class).name();    
    		}
    		//       
    		if (ArrayUtils.isNotEmpty(title)) {
    			writer.writeRecord(title); 
    		}
    		writer.close();
    		//     
    		ServletOutputStream output = response.getOutputStream();
    		response.setContentType("application/csv;charset=UTF-8");  
    		response.setHeader("Access-Control-Allow-Origin", "*");
    		response.setHeader("Access-Control-Expose-Headers", "*");
    		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".csv");
    		int len = -1;
    		byte[] b = new byte[1024 * 1024];
    		while((len = input.read(b)) != -1) {    
    			output.write(b, 0, len);
    		} 
    		output.close();
    	} catch (Exception e) {  
    		LOGGER.error("  CSV    ", e);  
    	} finally {  
    		deleteFile(path, TEMP_PATH);
    	}
    }
  
    /** 
     *   CSV     
     *  
     * @param filePath        , :D:/csv/xxx.csv 
     * @param bean     
     * @return List 
     */  
    public static  List readCSVFile(String filePath, Class bean) {  
        List dataList = new ArrayList();    
        CsvReader reader = null;  
        try {    
            //   CSV      :CsvReader(    ,   ,    );    
            reader = new CsvReader(filePath, ',', Charset.forName("GBK"));    
            if (reader != null) {  
                //     ,        ,          
                //reader.readHeaders();    
                //               
                while (reader.readRecord()) {    
                    dataList.add(reader.getValues());     
                }    
                if (!dataList.isEmpty()) {  
                    //        
                    return getBeanFromStringArray(dataList, bean);  
                }  
            }  
        } catch (Exception e) {    
            LOGGER.error("  CSV    ", e);    
        } finally {  
            if (reader != null) {  
                reader.close();   
            }  
        }  
        return Collections.emptyList();  
    }  
    
    /** 
     *            
     * 
     * @param filePath       , :d:/test 
     */  
    public static boolean deleteFiles(String filePath) {  
        File file = new File(filePath);  
        if (file.exists()) {  
            File[] files = file.listFiles();  
            if (files != null && files.length > 0) {  
                for (File f : files) {  
                    if (f.isFile() && f.delete()) {  
                        LOGGER.info("  " + f.getName() + "    ");  
                    }  
                }  
                return true;  
            }  
        }  
        return false;  
    }  
  
    /** 
     *        
     * 
     * @param filePath       , :d:/test 
     * @param fileName     , :110.csv 
     */  
    public static boolean deleteFile(String filePath, String fileName) {  
        File file = new File(filePath);  
        if (file.exists()) {  
            File[] files = file.listFiles();  
            if (files != null && files.length > 0) {  
                for (File f : files) {  
                    if (f.isFile() && f.getName().equals(fileName)) {  
                        return f.delete();  
                    }  
                }  
            }  
        }  
        return false;  
    }  
      
    /** 
     *           
     * 
     * @param beans      
     * @return List 
     */  
    private static  List getStringArrayFromBean(List beans) {     
        List result = new ArrayList();          
        Class extends Object> cls = beans.get(0).getClass();    
        Field[] declaredFields = cls.getDeclaredFields();    
        List annoFields = new ArrayList();     
        //             
        for (Field field : declaredFields) {  
            CSVField anno = field.getAnnotation(CSVField.class);    
            if (anno != null) {   
                annoFields.add(field);    
            }  
        }   
        //       ,       
        String[] title = new String[annoFields.size()];       
        for (int i = 0; i < annoFields.size(); i++) {    
            title[i] = annoFields.get(i).getAnnotation(CSVField.class).name();    
        }    
        result.add(title);    
        try {  
            //       
            for (T t : beans) {    
                String[] item = new String[annoFields.size()];   
                int index = 0;  
                for (Field field : annoFields) {  
                	Class> valType = field.getType();
                    String fieldName = field.getName();  
                    String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);    
                    Method method = ReflectionUtils.findMethod(t.getClass(), methodName);  
                    if (method != null) {  
                        Object value = ReflectionUtils.invokeMethod(method, t);  
                        item[index] = setValues(value, valType);
                    }   
                    index ++;  
                }  
                result.add(item);           
            }  
        } catch (Exception e) {  
            LOGGER.info("         ", e);  
        }    
        return result;    
    }  
      
    /** 
     *          
     * 
     * @param dataList     
     * @param bean    
     * @return List 
     */  
    private static  List getBeanFromStringArray(List dataList, Class bean) {  
        List list = new ArrayList<>();  
        List> titles = getTitles(dataList);  
        Map fields = getFields(bean);  
        try {  
            for (Map map : titles) {  
                T t = bean.newInstance();  
                for (Entry entry : map.entrySet()) {  
                    if (fields.containsKey(entry.getKey())) {  
                        Field field = fields.get(entry.getKey());  
                        Class> valType = field.getType(); 
                        Object value = getType(entry.getValue(), valType);
                        String fieldName = field.getName();                                                     
                        String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);    
                        Method method = ReflectionUtils.findMethod(bean, methodName, valType);  
                        if (method != null) {  
                            ReflectionUtils.invokeMethod(method, t, value);  
                        }  
                    }  
                }  
                list.add(t);  
            }  
        } catch (Exception e) {  
            LOGGER.error("      ", e);  
        }  
        return list;  
    }  
      
    /** 
     *             
     * 
     * @param dataList     
     * @return 
     */  
    private static  List> getTitles(List dataList) {  
        List> list = new ArrayList<>();  
        String[] titles = dataList.get(0);  
        dataList.remove(0);  
        for (String[] values : dataList) {  
            Map titleMap = new HashMap<>();  
            for (int i = 0; i < values.length; i++) {  
                titleMap.put(titles[i], values[i]);  
            }  
            list.add(titleMap);  
        }  
        return list;  
    }  
      
    /** 
     *                
     *   
     * @param clazz         
     * @param       
     * @return Map 
     */  
    private static  Map getFields(Class clazz) {  
        Map annoMap = new HashMap<>();  
        Field[] fileds = clazz.getDeclaredFields();  
        for (Field filed : fileds) {  
            CSVField anno = filed.getAnnotation(CSVField.class);  
            if (anno != null) {  
                //   name     
                if (StringUtils.isNotBlank(anno.name())) {  
                    annoMap.put(anno.name(), filed);  
                }  
            }  
        }  
        return annoMap;  
    }
    
    /**
     *    
     * 
     * @param value    
     * @param valType     
     * @return
     */
    private static String setValues(Object value, Class> valType) {
    	if (value == null) {                            
            return "";  
        } else if (valType == Date.class) {
        	//         :yyyy-MM-dd HH:mm:ss
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
            return sdf.format(((Date) value).getTime());  
            
        } else { //      
        	return String.valueOf(value);  
        }
    }
    
    /** 
     *              
     *   
     * @param value        
     * @param valType        
     * @return Object         obj   
     */  
    private static  Object getType(String value, Class valType) {  
        try {  
            if (valType == Date.class) {   
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
                return sdf.parse(value);  
            } else if (valType == Double.class) {    
                return Double.parseDouble(value);    
            } else if (valType == BigDecimal.class) {    
                return new BigDecimal(value);    
            } else if (valType == Integer.class) {    
                return Integer.parseInt(value);    
            } else if (valType == Long.class) {    
                return Long.parseLong(value);    
            } else if (valType == Boolean.class) {    
                return Boolean.parseBoolean(value);    
            }   
        } catch (Exception e) {  
            LOGGER.error("      ", e);  
        }  
        return value;    
    }
        
    /** 
     *       
     * 
     * @param filePath     ,  :temp/test.csv 
     */  
    private static void createDir(String filePath) {  
        try {  
        	File file = new File(filePath.substring(0, filePath.lastIndexOf('/')));  
            if (!file.exists()) {  
                file.mkdirs();  
            }         
        } catch (Exception e) {  
            LOGGER.error("        ", e);  
        }  
    }  
    
    /** 
     *     
     * 
     * @param filePath     ,  :temp/test.csv 
     * @return File 
     */  
    private static File createFile(String filePath) {  
    	try {  
    		File file = new File(filePath);  
    		if (!file.exists()) {
    			file.createNewFile();
    		} 
    		return file;
    	} catch (Exception e) {  
    		LOGGER.error("      ", e);  
    	} 
    	return null;
    }  
    
}

 
 
 
 

좋은 웹페이지 즐겨찾기