Java实现数据导出Excel

来源:互联网 发布:网络借贷暂行办法解读 编辑:程序博客网 时间:2024/05/22 12:09

实现步骤:

  1. 获取需要导出的数据集合
  2. 创建一个Map对象,格式对应导出的Excel格式
  3. 通过jxl包下 WritableWorkbook来创建Excel
  4. 输出流输出Excel另存为到本地目录

    创建Excel格式Map对象代码示例:

    Excel中的数据容器,!!值得注意的是fileMap中的key要和表格中的表头的英文名数据一一对应才行
    如果需要的是引用对象的某个属性,则英文属性使用的是类似于EL表达式的格式
    如我们存储的是student,但是在student中要存储班级名称,班级是个对象,这个时候我们就可以这样实现
    fileMap.put(“Calzz.name”,”学生所在班级”);

  //key必须对应数据集中键名  value对应Excel创建的表格标题 LinkedHashMap<String, String> fieldMap = new LinkedHashMap<String, String>(); fieldMap.put("mc","名称"); fieldMap.put("xh","学号"); fieldMap.put("xm","姓名"); fieldMap.put("sfzh","身份证号"); fieldMap.put("xb","性别"); fieldMap.put("xl","学历"); fieldMap.put("xy","学院"); fieldMap.put("PROFESSION.zy","专业");

代码示例:

File file=new File( DateFormatUtils.format(new Date(),"yyyyMMddHHmm")+".xls");        System.out.println("file path="+file.getPath());        FileOutputStream fos=null;        try {            if (!file.exists()) {//文件不存在 则创建一个                file.createNewFile();            }            fos = new FileOutputStream(file);            ExcelUitl.listToExcel(exportList, fieldMap, file.getName(), exportList.size(), fos);            HttpServletResponse response = context.getResponse();            excel(response,file);        } catch (IOException e) {            e.printStackTrace();        }catch (ExcelException e){        }/**     * 输出文件     * @param response     * @param file     */    public void excel(HttpServletResponse response,File file){        BufferedInputStream dis = null;        BufferedOutputStream fos = null;        try {            response.setContentType("application/vnd.ms-excel");            getContext().getResponse().addHeader("Content-Disposition", "attachment;filename=" + DateFormatUtils.format(new Date(),"yyyyMMddHHmm")+".xls");            getContext().getResponse().addHeader("Content-Length", "" + file.length());            dis = new BufferedInputStream(new FileInputStream(file));            fos = new BufferedOutputStream(response.getOutputStream());            byte[] buff = new byte[2048];            int bytesRead;            while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {                fos.write(buff, 0, bytesRead);            }            dis.close();            fos.close();        } catch (Exception e) {        } finally {            if (dis != null){                try{                    dis.close();                }catch (Exception e){                    e.printStackTrace();                }            }            if (fos != null){                try{                    fos.close();                }catch (Exception e){                    e.printStackTrace();                }            }        }    }

资源下载:ExcelUitl和jar包

原创粉丝点击