java 导入导出excel

一,导出excel

1,使用excel模板

public void exportLog() throws Exception{
        SystemUser currentUsr = getCurrentSystemUser();
        
        //该用户的所有日志
        List<TLogInfo> loglist=logService.getLogInfosByUserId(currentUsr.getId());
        
        List<TLogInfo> list=new ArrayList<TLogInfo>();
        if(loglist!=null && loglist.size()>0){
            for(TLogInfo log:loglist){
                TLogInfo export=new TLogInfo();
                export.setProName(log.getProName());
                export.setLogTitle(log.getLogTitle());
                export.setLogType(log.getLogType());
                export.setWorkTime(log.getWorkTime());
                export.setLogFillTime(log.getLogFillTime());
                list.add(export);
            }
        }
        String templateFileName = "xlstemp/personallog.xls";
        String resultFileName = "xlsresult/personallog.xls";
        String path = ExcelUtil.createExcel(templateFileName, list,
                resultFileName);
        File file = new File(path);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        downloadFile("信息.xls", bytes);
        file.deleteOnExit();        
        
    }
 ExcelUtil类的createExcel方法
public static String createExcel(String templateFileName, List<?> list,
            String resultFileName) {
        // 创建XLSTransformer对象
        XLSTransformer transformer = new XLSTransformer();
        // 获取java项目编译后根路径
        String class_path = ExcelUtil.class.getClassLoader().getResource("").getPath();
        // 得到模板文件路径
        String srcFilePath = class_path + templateFileName;
        Map<String, Object> beanParams = new HashMap<String, Object>();
        beanParams.put("list", list);
        String destFilePath = class_path + resultFileName;
        try {
            // 生成Excel文件
            transformer.transformXLS(srcFilePath, beanParams, destFilePath);
            return destFilePath;
        } catch (ParsePropertyException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

 

2,使用poi.jar
Object property = PropertyUtils.getProperty(bean, fieldName); //获取对象中指定字段的值

 


二,导入excel
构造一个map集合,(用户名,username)
读取表头时,根据键得到对应的value,即保存到对象时要用到的字段名,构造一个字段列表,以后遍历每一行的内容,可找相对应的索引的字段名,这样就可以将值保存到对象中
String typeName = PropertyUtils.getPropertyType(bean, name).getName(); //有时要对特殊字段类型进行转换

 

















posted @ 2014-10-23 13:55  野鹤闲人  阅读(282)  评论(0编辑  收藏  举报