jxl通过模板生成excel报表并下载


    @RequestMapping(value="exportSummarizeXls")
    public void exportSummarizeXls(HttpServletRequest request,
             HttpServletResponse response, String navTabId,
             @RequestParam Map<String, Object> params,PageConfig pageConfig,String orderField,String orderDirection ) throws Exception{
        
        String tjqjq = MapGetter.getString(params,"tjqjq");
        String tjqjz = MapGetter.getString(params,"tjqjz"); 
        String nsrsbh = MapGetter.getString(params,"summarizeNsrsbh");
        
        //转换时间格式为"yyyyMM"类型
       tjqjq = tjqjq.replace("-", "");
       tjqjz =  tjqjz.replace("-", "");
        
        //获取查询数量
        int count = summarizeService.getCompanyCount(params);
        //初始化分页对象
         HibernatePageBean pageBean = new HibernatePageBean(1, count, 0, 3000);
        pageBean.jumpTo(1);
        List<Map<String,Object>> list = summarizeService.getSummarizeList(pageBean,orderField,orderDirection,params);
        
        
        /*模板存放路径*/
        String modelPath = System.getProperty("user.dir").replace("bin", "webapps")+"\\excelExportModel\\";
        String[] bodyNames=new String[]{"nsrsbh","shopName","gtxiaoshoue","gtshuie","zyxiaoshoue","zyshuie","lyxiaoshoue","lyshuie","xsze","xsse","fpze","fpse","ssce"};
        int headerRowSize=3;
        modelPath=modelPath+"hz.xls";
        String filePath = "ExcelFile\\"+"销售汇总统计表";
        String fileName = nsrsbh+"_销售汇总统计表_"+tjqjq+"月至"+tjqjz+"月";
        filePath = System.getProperty("user.dir").replace("bin", "webapps")+"\\"+filePath;
        /*为了保证目录存在,如果没有则新建该目录 */
        File excelFile = new File(filePath); 
        if (!excelFile.exists()) {
            excelFile.mkdirs(); 
        }
        try {
        /* 第一步:读取模板*/
        Workbook wb = Workbook.getWorkbook(new File(modelPath));
        /* 第二步:通过模板得到一个可写的Workbook:第一个参数是一个输出流对象,第二个参数代表了要读取的模板*/
        File targetFile = new File(filePath+"\\"+fileName+".xls");
        WritableWorkbook wwb = Workbook.createWorkbook(targetFile, wb);
        /* 第三步:选择模板的Sheet*/
        WritableSheet wws = wwb.getSheet(0);
        
        /*String[] nsrsbh = sid.split(",");
        List<Map<String,Object>> summarizeList = (List<Map<String, Object>>) request.getSession().getAttribute("summarizeList");
        ArrayList<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        for (int i = 0; i < nsrsbh.length; i++) {
            String nsrsbhStr = nsrsbh[i];
            for (Map<String, Object> summarizeMap : summarizeList) {
                if(nsrsbhStr.equals(MapGetter.getString(summarizeMap, "nsrsbh"))){
                    list.add(summarizeMap);
                }
            }
        }*/
    
        /*数据内容填充*/
        for (int i = 0; i < list.size(); i++) {
            /*序号列填充,headerRowSize+i表示从表头结束后的一行开始填充数据*/
            jxl.write.Label label0 = new jxl.write.Label(0, headerRowSize+i, i+1+"");
            wws.addCell(label0);
            /*遍历list并按bodyNames顺序获取数据填充到单元格内*/
            Map map =  (Map)list.get(i);
            for (int j = 0,k=1; j < bodyNames.length; j++) {
                 Object object = map.get(bodyNames[j]);
                 String val = "";
                 if (object instanceof Timestamp) {
                     Timestamp timestamp = (Timestamp)object;
                     Date date = new Date();
                     date.setTime(timestamp.getTime());
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    val = simpleDateFormat.format(date);
                }else if (object instanceof Date) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    val = simpleDateFormat.format(object);
                }else {
                    val = String.valueOf(map.get(bodyNames[j]));
                }
                 if (val == null || "null".equals(val)) {
                    val = "";
                }
                jxl.write.Label label1 = new jxl.write.Label(k++, headerRowSize+i, val);
                wws.addCell(label1);
            }
        }
        wwb.write();
        wwb.close();
        wb.close();
        
            //下载生成好的excel文件
            String realPath = filePath;
            String path = filePath+"\\"+fileName+".xls";
            File file = new File(path);
            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"ISO-8859-1" )+".xls");
            byte[] buff = new byte[1024];
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = 0;
                while ((i = bis.read(buff)) != -1) {
                    os.write(buff, 0, i);
                    os.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
      
        } catch (Exception e) {
            e.printStackTrace();
        }
        

    }

猜你喜欢

转载自blog.csdn.net/chenglaozong/article/details/83542095