1. 程式人生 > >java 實現的excel資料的匯入匯出

java 實現的excel資料的匯入匯出

/**
     * 匯出
     * @param user
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("persion:infoTbPersonLive:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(InfoTbPersonLive infoTbPersonLive, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        /*try {
            String fileName = "建築資料"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<InfoTbPersonLive> page = infoTbPersonLiveService.exportList(new Page<InfoTbPersonLive>(request, response, -1), infoTbPersonLive);
            new ExportExcel("建築資料", InfoTbPersonLive.class).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "匯出建築失敗!失敗資訊:"+e.getMessage());
            e.printStackTrace();
        }
        return "redirect:"+Global.getAdminPath()+"/persion/infoTbPersonLive/?repage";*/
        OutputStreamWriter writer = null;
        try
        {
            //先載入字典
            Map<String,String> floorTypeMap = new HashMap<String,String>();
            for(Dict target:DictUtils.getDictList("BUILDING_FLOOR_TYPE"))
            {
                floorTypeMap.put(target.getValue(), target.getLabel());
            }
            
            Map<String,String> sexMap = new HashMap<String,String>();
            for(Dict target:DictUtils.getDictList("PERSON_SEX"))
            {
                sexMap.put(target.getValue(), target.getLabel());
            }
            
            Map<String,String> nationMap = new HashMap<String,String>();
            for(Dict target:DictUtils.getDictList("PERSON_NATION"))
            {
                nationMap.put(target.getValue(), target.getLabel());
            }
            
            Map<String,String> subjectTypeMap = new HashMap<String,String>();
            for(Dict target:DictUtils.getDictList("SUBJECT_TYPE"))
            {
                subjectTypeMap.put(target.getValue(), target.getLabel());
            }
            
            Map<String,String> liveRelationMap = new HashMap<String,String>();
            for(Dict target:DictUtils.getDictList("LIVE_RELATION"))
            {
                liveRelationMap.put(target.getValue(), target.getLabel());
            }
            
            Map<String,String> liveWayMap = new HashMap<String,String>();
            for(Dict target:DictUtils.getDictList("LIVE_WAY"))
            {
                liveWayMap.put(target.getValue(), target.getLabel());
            }
            
            Map<String,String> liveReasonMap = new HashMap<String,String>();
            for(Dict target:DictUtils.getDictList("LIVE_REASON"))
            {
                liveReasonMap.put(target.getValue(), target.getLabel());
            }
            
            Map<String,String> domicileTypeMap = new HashMap<String,String>();
            for(Dict target:DictUtils.getDictList("PERSON_DOMICILE_TYPE"))
            {
                domicileTypeMap.put(target.getValue(), target.getLabel());
            }
            
            Map<String,String> yesNoMap = new HashMap<String,String>();
            for(Dict target:DictUtils.getDictList("YES_NO"))
            {
                yesNoMap.put(target.getValue(), target.getLabel());
            }
            
            String name = "居住資訊";
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            String filename = new String((name + "匯出.xls").getBytes("GBK"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment;Filename=" + filename);
            
            long startTimne = System.currentTimeMillis();
            
            StringTemplateGroup stGroup = new StringTemplateGroup("stringTemplate");    
            stGroup.setFileCharEncoding("utf-8");
            
            //寫入excel檔案頭部資訊
            StringTemplate head =  stGroup.getInstanceOf("com/amass/basicdata/common/excel/head");
            writer = new OutputStreamWriter(new BufferedOutputStream(response.getOutputStream()),"utf-8");
            writer.write(head.toString());
            writer.flush();
            
            Page<InfoTbPersonLive> page = new Page<InfoTbPersonLive>(request, response);
            page.setPageSize(5000);
            
            int count = infoTbPersonLiveService.findCount(infoTbPersonLive).getCount();
            System.out.println("共"+count+"條資料");
            int forcnt = count/page.getPageSize() + (count%page.getPageSize()==0?0:1);
            if(forcnt == 0)
            {
                forcnt = 1;
            }
            
            for(int i=0;i<forcnt;i++)
            {
                StringTemplate body =  stGroup.getInstanceOf("com/amass/basicdata/common/excel/personLivebody");
                Worksheet<InfoTbPersonLive> worksheet = new Worksheet<InfoTbPersonLive>();
                worksheet.setSheet(name+(i+1));
                worksheet.setColumnNum(26);
                worksheet.setRowNum(page.getPageSize()+3);
                worksheet.setTitle(name);
                
                worksheet.setRows(infoTbPersonLiveService.exportList(page,infoTbPersonLive).getList());
                for(int j=0;j<worksheet.getRows().size();j++)
                {
                    InfoTbPersonLive row = worksheet.getRows().get(j);
                    if(row.getFloorFloorType() != null && StringUtils.isNotBlank(row.getFloorFloorType().getFloorType()))
                    {
                        row.getFloorFloorType().setFloorType(floorTypeMap.get(row.getFloorFloorType().getFloorType()));
                    }
                    
                    if(row.getPersonsex() != null && StringUtils.isNotBlank(row.getPersonsex()))
                    {
                        row.setPersonsex(sexMap.get(row.getPersonsex()));
                    }
                    
                    if(row.getPersonnation() != null && StringUtils.isNotBlank(row.getPersonnation()))
                    {
                        row.setPersonnation(nationMap.get(row.getPersonnation()));
                    }
                    
                    if(row.getSubjectType() != null && StringUtils.isNotBlank(row.getSubjectType()))
                    {
                        row.setSubjectType(subjectTypeMap.get(row.getSubjectType()));
                    }
                    
                    if(row.getRelationWithHouseholder() != null && StringUtils.isNotBlank(row.getRelationWithHouseholder()))
                    {
                        row.setRelationWithHouseholder(liveRelationMap.get(row.getRelationWithHouseholder()));
                    }
                    
                    if(row.getLiveWay() != null && StringUtils.isNotBlank(row.getLiveWay()))
                    {
                        row.setLiveWay(liveWayMap.get(row.getLiveWay()));
                    }
                    
                    if(row.getLiveReason() != null && StringUtils.isNotBlank(row.getLiveReason()))
                    {
                        row.setLiveReason(liveReasonMap.get(row.getLiveReason()));
                    }
                    
                    if(row.getLiveWhere() != null && StringUtils.isNotBlank(row.getLiveWhere()))
                    {
                        row.setLiveWhere(domicileTypeMap.get(row.getLiveWhere()));
                    }
                    
                    if(row.getHaveInsurance() != null && StringUtils.isNotBlank(row.getHaveInsurance()))
                    {
                        row.setHaveInsurance(yesNoMap.get(row.getHaveInsurance()));
                    }
                }
                body.setAttribute("worksheet", worksheet);
                
                writer.write(body.toString());
                writer.flush();
                worksheet = null;
                body = null;
                Runtime.getRuntime().gc();
                System.out.println("正在生成excel檔案的 sheet"+(i+1));
                
                page.setPageNo(page.getPageNo()+1);
            }
            
            //寫入excel檔案尾部
            writer.write("</Workbook>");
            writer.flush();
            writer.close();
            System.out.println("生成excel檔案完成");
            long endTime = System.currentTimeMillis();
            System.out.println("用時="+((endTime-startTimne)/1000)+"秒");
        }
        catch (IOException e1)
        {
            System.out.println("使用者已中斷操作");
        }
        finally
        {
            if(writer != null)
            {
                try {
                    writer.close();
                } catch (IOException e) {}
            }
        }
        return null;
    }