opencsv 对文件的读写

/**
 * 
 * CSV文件导出工具类
 * 
 * Created on 2014-08-07
 * @author 
 * @reviewer 
 */
public class CsvUtils {

    /**
     * CSV文件生成方法
     * @param head
     * @param dataList
     * @param outPutPath
     * @param filename
     * @return 
     * @return
     */
    public static <T> void createCSVFile( LinkedHashMap<String, String> fieldMap,List<T> list,
    		 HttpServletResponse response) {        
     // 设置默认文件名为当前时间:年月日时分秒
        String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();

        // 设置response头信息
        response.reset();
        response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".csv");
        OutputStream out = null;
        try {
        	out=response.getOutputStream();
            List<Object> headList = new ArrayList<Object>();
            String[] enFields = new String[fieldMap.size()];
            int count = 0;
            for (Entry<String, String> entry : fieldMap.entrySet()) {
            	headList.add(entry.getValue()) ;
            	enFields[count] = entry.getKey();
                count++;
            }
            writeRow(headList,list, out,enFields);

        } catch (Exception e) {
        	new BusinessException("导出csv失败");
        } finally {
        	try {
        		out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

	/**
     * 写一行数据方法
     * @param <T>
     * @param row
     * @param csvWriter
     * @throws Exception 
     */
    private static <T> void writeRow(List<Object> headList,List<T> row, OutputStream out,String[] enFields) throws Exception {
    	// 写入文件头部
    	StringBuffer head = new StringBuffer();
    	for (int i = 0; i < headList.size(); i++) {
    		Object data=headList.get(i);
    		head.append("\"").append(data);
    		if(i<headList.size()-1){
    			head.append("\",");
    		}else{
    			head.append("\"");
    		}
		}
    	out.write(head.toString().getBytes());
    	out.write("\r\n".getBytes());
        for (T item : row) {
        	Object data = null;
        	StringBuffer sb = new StringBuffer();
        	for (int i = 0; i < enFields.length; i++) {
        		data = getFieldValueByNameSequence(enFields[i], item);
        		String fieldValue = data == null ? "" : data.toString();
        		sb.append("\"").append(fieldValue);
        		if(i<enFields.length-1){
        			sb.append("\",");
        		}else{
        			sb.append("\"");
        		}
        	}
            out.write(sb.toString().getBytes());
            out.write("\r\n".getBytes());
        }
    }
    
    /**
     * @param fieldNameSequence 带路径的属性名或简单属性名
     * @param o                 对象
     * @return 属性值
     * @throws Exception
     * @MethodName : getFieldValueByNameSequence
     * @Description : 根据带路径或不带路径的属性名获取属性值
     * 即接受简单属性名,如userName等,又接受带路径的属性名,如student.department.name等
     */
    private static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception {

        Object value = null;

        // 将fieldNameSequence进行拆分
        String[] attributes = fieldNameSequence.split("\\.");
        if (attributes.length == 1) {
            value = getFieldValueByName(fieldNameSequence, o);
        } else {
            // 根据属性名获取属性对象,递归获取值
            Object fieldObj = getFieldValueByName(attributes[0], o);
            String subFieldNameSequence = fieldNameSequence.substring(fieldNameSequence.indexOf(".") + 1);
            // 递归调用的时候,那个值可能没有,在这里就会报空指针异常
            if(!ObjectUtils.isEmpty(fieldObj)) {
                value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
            }
        }
        return value;

    }
    
    /**
     * @param fieldName 字段名
     * @param o         对象
     * @return 字段值
     * @MethodName : getFieldValueByName
     * @Description : 根据字段名获取字段值
     */
    public static Object getFieldValueByName(String fieldName, Object o) throws Exception {
        Object value = null;
        //Field field = getFieldByName(fieldName, o.getClass());
        try{
            Field field = o.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            value = field.get(o);
        }catch(NoSuchFieldException e){
            String methodName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
            Method method = o.getClass().getMethod(methodName);
            value=method.invoke(o);
        }
        return value;
    }
    
    
    
    /**
     * 解析csv文件并转成bean
     * @param file csv文件
     * @param clazz 类
     * @param <T> 泛型
     * @return 泛型bean集合
     */
    public static <T> List<T> getCsvData(InputStream inputStream, Class<T> clazz) {
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(inputStream, "utf-8");
        } catch (Exception e) {
        	new BusinessException("导人csv失败");
        }
        
        HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
        strategy.setType(clazz);
        /*
            withSkipLines 跳过前几行
            withQuoteChar 过滤字符
         */
        CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(in).withSkipLines(1)
                .withSeparator(',')
                .withQuoteChar('\"')
                .withType(clazz).build();
        return csvToBean.parse();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值