线程导出

来源:互联网 发布:冒险岛游戏数据 编辑:程序博客网 时间:2024/06/06 00:17
package com.chinahrt.controller;
 
import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chinahrt.common.BusinessConfig;
import com.chinahrt.service.ExportAsyncService;
import com.chinahrt.service.RedisService;
import com.chinahrt.util.UUIDUtil;
import com.chinahrt.vo.SessionInfo;
@Controller
@RequestMapping("/export_data")
public class ExportAsyncController extends ReportBaseController{

@Resource
    private ExportAsyncService exportAsyncService;

@Resource
    private RedisService redisSerivce;

@Resource
    private BusinessConfig businessConfig;

@RequestMapping("/export_jsp")
    public String export(HttpServletRequest request,HttpServletResponse response,Model model){
         return "export";
    }
    @RequestMapping("/to_lookProcess")
    public String lookProcess(HttpServletRequest request,HttpServletResponse response,Model model,String moduleId){
         return "process";
    }

@RequestMapping("/getDownloadInfo")
    public void getDownloadInfo(HttpServletRequest request,HttpServletResponse response ) throws IOException{
ArrayList<Map<String,String>> flagList=new ArrayList<Map<String,String>>();
        String moduleId=businessConfig.getModuleId();
        SessionInfo session=getCurrentSessionInfo(request);
        String redisKey=businessConfig.getExportExcel()+"_"+session.getPlatFormId()+"_"+moduleId+"_"+session.getUserId();
        String redisAllMap = redisSerivce.getRedisAllMap(redisKey);
        Map<String,String> map =JSON.parseObject(redisAllMap, new TypeReference<Map<String,String>>(){});
        for (String key : map.keySet()) {
             flagList.add(JSON.parseObject(map.get(key), new TypeReference<Map<String,String>>(){}));
        }
        writeJson(response, flagList);
    }

@RequestMapping("/exportDetailExcel")
public void exportDetailExcel(HttpServletRequest request,HttpServletResponse response,String userName,
        String startOrderTime,String endOrderTime,String starTpayTime,
        String endTpayTime,String orderNo,String paytypeName,String orderStatus,
        String platformId,String exportParam) throws IOException, IllegalAccessException, InvocationTargetException, IntrospectionException{

    Data(request, response, userName, startOrderTime, endOrderTime, 
        starTpayTime, endTpayTime, orderNo, paytypeName, orderStatus, platformId, exportParam);
}

@RequestMapping("/Data")
    public String Data(HttpServletRequest request,HttpServletResponse response,String userName,
                        String startOrderTime,String endOrderTime,String starTpayTime,
                        String endTpayTime,String orderNo,String paytypeName,String orderStatus,
                        String platformId,String expor) throws IOException, IllegalAccessException, InvocationTargetException, IntrospectionException{
//导出
        SessionInfo session=getCurrentSessionInfo(request);
        Map<String,Object>  result=new HashMap<String, Object>();
                String moduleId=businessConfig.getModuleId();  
                List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("invoiceTime", "1");
                map.put("orderMoney", "1");
                map.put("payTime", "1");
                map.put("discount", "1");
                map.put("orderStatus", "1");
                map.put("resid", "1");
                map.put("payPoints", "1");
                map.put("orderTime", "1");
                map.put("payMoney", "1");
                map.put("orderStatusStr", "1");
                map.put("orderPoints", "1");
                map.put("finnshedTime", "1");
                map.put("outSn", "1");
                map.put("id", "1");
                map.put("platformName", "1");
                map.put("mobAndEml", "1");
                map.put("email", "1");
                map.put("payMessage", "1");
                map.put("orderPointscount", "1");
                map.put("refundState", "1");
                map.put("orderNo", "1");
                map.put("payTypeNames", "1");
                map.put("payDirect", "1");
                map.put("paytypeName", "1");
                map.put("refundMoney", "1");
                map.put("platformId", "1");
                map.put("dealNo", "1");
                map.put("evaluationTime", "1");
                map.put("handingFee", "1");
                map.put("payAccount", "1");
                map.put("userName", "1");
                map.put("userId", "1");
                map.put("deviceInfo", "1");
                map.put("realName", "1");
                map.put("detailList", "1");
                map.put("orderInfo", "1");
                map.put("paytypeId", "1");
                map.put("invoiceId", "1");
                map.put("orderFrom", "1");
                map.put("invoiceStatus", "1");
                map.put("payCode", "1");
                map.put("evaluationStatus", "1");
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                list.add(map);
                LinkedHashMap<String,String> mapper=getExportMapper();
                exportAsyncService.exportListToExcel(list, mapper, session.getUserId(), session.getPlatFormId(),moduleId);
                result.put("res", "success");
                result.put("data", "");
            writeJson(response, result);
return null;
    }

private LinkedHashMap<String,String> getExportMapper(){
        LinkedHashMap<String,String> result=new LinkedHashMap<String, String>();
        result.put("orderNo", "订单号");
        result.put("userName", "用户名");
        result.put("paytypeName", "支付方式");
        result.put("payMoney", "支付金额(元)");
        result.put("orderMoney", " 订单金额(元)");
        result.put("orderTime", "下单时间");
        result.put("payTime", "付款时间");
        result.put("platformName", "平台");
        result.put("realName", "姓名");
        result.put("mobAndEml", "邮箱/手机");
        result.put("orderStatusStr", "订单状态");
        return result;
    }




    
    
 


}

//Service

package com.chinahrt.service;




import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


import javax.annotation.Resource;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;


import com.alibaba.fastjson.JSON;
import com.chinahrt.common.BaseException;
import com.chinahrt.common.BusinessConfig;
import com.chinahrt.util.UUIDUtil;


@Service
public class ExportAsyncService {
private static final Log log = LogFactory.getLog(ExportAsyncService.class);

@Resource
private RedisService redisService;

@Resource
    private BusinessConfig businessConfig;
    
     
    
    public void exportListToExcel(List<Map<String,Object>> lst,LinkedHashMap<String, String> keyMap,String userId, String platformId,String module){
    String redisKey=businessConfig.getExportExcel()+"_"+platformId+"_"+module+"_"+userId;
        ExportCVSThread t=new ExportCVSThread(lst, keyMap,platformId,module,userId,redisKey);
        t.start();
    }
    
    class  ExportCVSThread extends Thread{
        private  List<Map<String,Object>> map;
        private String platformId;
        private String moduleId;
        private String userId;
        private LinkedHashMap<String, String> keyMap;
        private String redisKey;
        
        public ExportCVSThread(List<Map<String,Object>> map,LinkedHashMap<String, String> keyMap, String platformId,String moduleId,String userId,String redisKey){
            this.map=map;
            this.keyMap=keyMap;
            this.platformId=platformId;
            this.moduleId=moduleId;
            this.userId=userId;
            this.redisKey=redisKey;
        }
        
        public void run(){
        String folder=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String tempFile=UUIDUtil.getUUID();
            String sto=businessConfig.getBasedirUpload()+File.separator+businessConfig.getFolderExportemp()+File.separator+folder;
            File filepaht1 = new File(sto);
            if (!filepaht1.exists()) {
                filepaht1.mkdirs();
            }
            sto=sto+File.separator+tempFile+".xls";
            String showFileName=tempFile+".xls";
            String showFileTime=new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(new Date());
            createCSVFile(map, keyMap, sto,redisKey,showFileName,showFileTime,folder,tempFile);
            
        }
    }
  
    private  File createCSVFile(List<Map<String, Object>> map, LinkedHashMap<String,String> rowMapper, String filename,String redisKey,String showFileName,String showFileTime,String folder,String tempFile) {
        File xlsFile = null;
        try {
            xlsFile = new File(filename);
            File parent = xlsFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
 
            
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("sheet1");
            HSSFCellStyle cellStyle = workbook.createCellStyle();
//            cellStyle.setFillBackgroundColor(new HSSFColor.DARK_GREEN().getIndex());
//            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//            cellStyle.setFillForegroundColor(new HSSFColor.GREEN().getIndex());
            
         // 生成一个字体
            HSSFFont font = workbook.createFont();
            font.setFontHeightInPoints((short) 10);
            //font.setColor(HSSFColor.RED.index);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            font.setFontName("宋体");
            cellStyle.setFont(font);
             
            
         // 写入文件头部
            HSSFRow headRow = sheet.createRow(0);
            int h=0;
            for (Map.Entry<String, String> entry : rowMapper.entrySet()) {
                HSSFCell cell = headRow.createCell(h);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(entry.getValue()); 
                h=h+1;
            }
            JSONObject json = new JSONObject();
            String field=UUIDUtil.getUUID();
            //json.put("total", map.size());
            //json.put("finish", 0);
            json.put("downValue", 0);
            json.put("showFileName", showFileName);
            json.put("showFileTime", showFileTime);
            json.put("downUrl",businessConfig.getBasedirLook()+"/"+businessConfig.getFolderExportemp()+"/"+ folder+"/"+tempFile+".xls");
            redisService.setMapValueToRedisByFiled(redisKey, field, json.toString());
            int i=1;
            for (Map<String, Object> m:map) {
                HSSFRow dataRow = sheet.createRow(i);
                int j=0;
                for (Map.Entry<String, String> property : rowMapper.entrySet()) {
                    HSSFCell cell = dataRow.createCell(j);
                    Object content= m.get(property.getKey());
                    if(content==null) content="";
 
                    //if(!(content instanceof String) && isNumeric(content.toString())) {
                    if((content instanceof Double)) {
                        cell.setCellValue((Double)content);
                    } else if(content instanceof Date) {
                        cell.setCellValue((Date)content);
                    }else {
                        cell.setCellValue(content.toString());
                    }
                    j=j+1;
                }
                i=i+1; 
                json.put("downValue",(i-1)*100/ map.size());
                redisService.setMapValueToRedisByFiled(redisKey, field, json.toString());
                redisService.expireRedis(redisKey,259200);
                Thread.sleep(1000);
                //TODO:测试
            }
           
            
            OutputStream out = new FileOutputStream(new File(filename));
            workbook.write(out);
            out.close();  
            Thread.sleep(1000);
        } 
        catch (Exception e) {
            log.error(e.getMessage(),e);
        } 
//        finally {
//            try {
//                if(csvFileOutputStream!=null) csvFileOutputStream.close();
//            } catch (IOException e) {
//                log.error(e.getMessage(),e);
//            }
//        }
        return xlsFile;
    }
   
    
}

//页面

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>test</title>
<#include "/common/web-inc.ftl"/>


<style>
.ui-front {
    z-index: 110000003;
}
</style>
<link type="text/css" rel="stylesheet" href="/js/ztree/css/zTreeStyle/zTreeStyle.css"/>




<script src="/js/ztree/js/jquery.ztree.core.js"></script>
<script src="/js/ztree/js/jquery.ztree.excheck.js"></script>
<script src="/js/jquery.chinahrt.orgctl.js"></script>
<script src="/js/jquery.chinahrt.trainplan.js"></script>
<script src="/js/jquery.chinahrt.platform.js"></script>
<script src="/js/jquery.chinahrt.date.js"></script>
<script src="/js/jquery.chinahrt.combo.js"></script>


</head>


<script type="text/javascript">
var waitDialog;
jQuery(function($){
    waitDialog=$("#chekWin").exportexcel({url:"/text_report/exportProcess"});
     
       });

function exportExcel(){


$.messager.confirm('确认','确认要导出吗?',function(r){
if(r){
exportFun();
}
});
}

function exportFun(){
$.ajax({   
url:'/export_data/exportDetailExcel',
  async:true,
  type:'POST',
  dataType:"json",
  data:{
          
      },
      success: function (data) {
        if(data.res=="success") {
           $.messager.alert('提示信息','正在导出ing','warning');
        }
        else{
        waitDialog.exportexcel("loadingClose");
        $.messager.alert('提示信息',data.data,'warning');
        }
        } 
         
    });  
}

function chakan(){
   location.href="/export_data/to_lookProcess";
}


</script>
<body>
<div class="easyui-layout"  data-options="fit:true"> 
     <div id="divFind" data-options="region:'north' " title="" style="height:205px;_height:215px;">
      <input type="button" value="导出1" onclick="exportExcel()" />
      <input id="cha" style="display: none; type="" value=""/>
      <input type="button" value="查看进度" onclick="chakan()" />
     </div>
     
     <div data-options="region:'center'"> 
         <table id="divData"> </table> 
      </div>
    
</div>
<div id="chekWin"   title="等待"  style="display: none;padding: 10px;"></div> 
</body>
</html>

//查看进度页面

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>test</title>
<#include "/common/web-inc.ftl"/>


<style>
.ui-front {
    z-index: 110000003;
}
</style>
<link type="text/css" rel="stylesheet" href="/js/ztree/css/zTreeStyle/zTreeStyle.css"/>




<script src="/js/ztree/js/jquery.ztree.core.js"></script>
<script src="/js/ztree/js/jquery.ztree.excheck.js"></script>
<script src="/js/jquery.chinahrt.orgctl.js"></script>
<script src="/js/jquery.chinahrt.trainplan.js"></script>
<script src="/js/jquery.chinahrt.platform.js"></script>
<script src="/js/jquery.chinahrt.date.js"></script>
<script src="/js/jquery.chinahrt.combo.js"></script>


</head>


<script type="text/javascript">
var num = 1;
function refreshProgress(){
var i= 0;
$.ajax({
   type: "POST",
   url: "/export_data/getDownloadInfo",
   data: "",
   success: function(data){
      var obj=JSON.parse(data);
      $.each(obj,function(index, n){
        var pname = "progress"+obj[index].showFileName.substring(0,10);
        var status="status"+obj[index].showFileName.substring(0,10);
                    if(num == 1){
      $("#td1").append("<tr><td>"+obj[index].showFileTime+"</td><td>"+obj[index].showFileName+"</td><td id='"+status+"'>生成中</td><td><div id='"+pname+"' name='p' value='"+obj[index].downValue+"' style='width: 150px; height: 20px;' class='easyui-progressbar progressbar'></td><td><input id='dwonUrl' style='display: none;' ' value='"+obj[index].downUrl+"' /><input id='btnSave' type='button' value='下载' class='basebtn btnsave' onClick='saveExcel();''/></td></tr>");
      }else{
      $("#"+pname).progressbar({
      value: obj[index].downValue
        });
        if(obj[index].downValue=="100"){
           $("#"+status).html('已完成');
           i=i+1;
        }
        if(i==obj.length){
          clearInterval(interval);
        }
        }
                   });
   }
});
num++;
}
var interval = setInterval(refreshProgress, "1000");
</script>
<script type="text/javascript">
function saveExcel(){
window.open($("#dwonUrl").val());
}
</script>
<body>
<div class="inputdq">
<form id="add_form" enctype="multipart/form-data" method="post"
style="font-size: 12px;">
<table>
<tr>
<td>申请时间</td>
<td>文件名</td>
<td>状态</td>
<td>进度条</td>
<td>操作</td>
</tr>
<tbody id="td1">

</tbody>
</table>
</form>
</div>
</body>
</html>




原创粉丝点击