SSM框架实现复杂的Excel导出功能

最近项目开发当中要求实现导出功能,查看了很多人的博客但是感觉对于复杂的导出还是感觉好麻烦,代码量太大,为此,想了多种方法,最后找到了最简洁的一种方法,如下:

1.要实现的导出功能模板如下:

本图片来自网络

2.按常规解决方法做如下导出显然是不明智的,为此,Java中提供了一个jar包可以实现这种复杂的导出

3.导入jxls包

本图片来自网络

4.在Controller中代码如下:

  • (1)首先实现数据查询
    本图片来自网络

  • (2)获取项目中放入Excel模板的路径以及导出Excel的路径
    本图片来自网络

  • (3)将项目路径放入读取流,导出路径以及文件名放入输出流,然后用Map实现key-value的方式写入Excel,此处的list和Detail是查询出来的结果集,然后就是用我们导入的jar包功能啦,使用XLSTransformer,将结果集写入Excel,然后在获取导出的文件路径,在客户端实现下载导出的功能
    本图片来自网络

  • 4.Excel模板如下,此处必须用${key.value}输出值的方式,否则无效
    本图片来自网络

5.附上源代码:

@RequestMapping(value = "/export.do",produces="text/html;charset=utf-8")
    @ResponseBody
    public void export(HttpServletRequest req,HttpServletResponse response) throws Exception {

        Long id = (long) Integer.parseInt(req.getParameter("id"));
        List<CustomsDeclareBill> list = customsDeclareBillService.selectByPrimaryKey(id);
        List<CustomsDeclareBillDetail> detail = customsDeclareBillDetailService.getSelectDetailById(list.get(0).getId());


        if(list!=null && !list.isEmpty()||detail!=null&&!detail.isEmpty()){
            InputStream is = null;
            OutputStream os = null;

            try {
                //文件名
                String excelName = "中华人民共和国海关进口货物报关单.xls";
                excelName = java.net.URLDecoder.decode(excelName,"utf-8");

                //获取Excel模板的路径
                /**
                 * 获取项目路径
                 * 1.this.getClass().getClassLoader().getResource("/").getPath();
                 * getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
                 * 2.req.getSession().getServletContext().getRealPath("/resources/upload");
                 * 3.servletContext.getRealPath("/").substring(0, servletContext.getRealPath("/").lastIndexOf("seawin-webapp-base"))
                 * */
                //String templateDir = "C:/Users/Administrator/Desktop/"+java.net.URLDecoder.decode(excelName,"utf-8");
                String templateDir =servletContext.getRealPath("/").substring(0, servletContext.getRealPath("/").lastIndexOf("seawin-webapp-base"))+"/seawin-pcweb/"+"/exceltemplates/" ;
                //导出Excel路径
                String exportDir=servletContext.getRealPath("/").substring(0, servletContext.getRealPath("/").lastIndexOf("seawin-webapp-base"))+"/seawin-uploadfile/";

                //设置响应  
                response.setCharacterEncoding("utf-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + new String(excelName.getBytes(), "ISO-8859-1"));  
                response.setContentType("application/vnd.ms-excel;charset=utf-8"); 


                 is = new FileInputStream(templateDir+excelName);
                 os = new FileOutputStream(exportDir+excelName);

                Map<String,Object> beans = new HashMap<String,Object>();
                beans.put("billlist", list);
                beans.put("detail", detail);

                XLSTransformer transFormer = new XLSTransformer();  
                HSSFWorkbook workBook = (HSSFWorkbook) transFormer.transformXLS(is, beans);  

                workBook.write(os);

                File file = new File(exportDir+File.separator+excelName);
                InputStream inputstream = null;
                if(file!=null){

                    inputstream = new FileInputStream(file);
                    //用于记录以完成的下载的数据量,单位是byte
                     long downloadedLength = 0l;

                      os=response.getOutputStream(); 
                    //循环写入输出流
                      byte[] b = new byte[2048];
                      int length;
                      while ((length = inputstream.read(b)) > 0) {
                          os.write(b, 0, length);
                          downloadedLength += b.length;
                      }

                }

                os.flush();
                inputstream.close();
                is.close();
                os.close();
            } catch (InvalidFormatException e) {  
                e.printStackTrace();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
}

好了,这样就可以实现导出功能了,再复杂的Excel导出使用此种方式都能够化繁为简,喜欢的小伙伴就将此文顶上去让更多人看到吧!

链接:http://blog.csdn.net/hu_shengyang/article/details/6736789,该链接写的很详细哦,并且可以实现往Excel中插入动态图片等等。


 上一篇
Eclipse导入maven项目报Resources文件夹红叉问题解决方案 Eclipse导入maven项目报Resources文件夹红叉问题解决方案
1.找到该项目下的settings文件夹, 2.找到该文件 3.打开查看版本号 与web.xml文件中的版本号做对比 4.然后在Eclipse中点击该项目maven update Project, OK! docu
2019-01-20
下一篇 
check the manual that corresponds to your MySQL server version for the right syntax to use near 'null' at line 84 check the manual that corresponds to your MySQL server version for the right syntax to use near 'null' at line 84
做mybatis批量插入的时候一直报这个错误,为此找了很久, 一直报着附近的错,后面发现是foreach后面括号没有添加,搞得我心累,所以还是粗心犯的错误, 出现这个错误肯定是sql语法的问题,建议仔细检查每一个环节才能找出错误
2019-01-20
  目录