解决方案 »

  1.   

    @SuppressWarnings("rawtypes")
    public void doExcel(List list,Class clazz,HttpServletResponse response,Map<String, String> map) throws Exception{
    //处理中文文件名称
      response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
        String fname = java.net.URLEncoder.encode("excel","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+new String(fname.getBytes("UTF-8"),"GBK")+".xls");
        response.setContentType("application/msexcel");//定义输出类型
        
        //获取输出流
    OutputStream os = response.getOutputStream();
    //创建工作簿
    WritableWorkbook wb = Workbook.createWorkbook(os);
    //创建第一页
    WritableSheet sheet = wb.createSheet("first", 0);
    //列的key数组
    String title[] =new String[]{};
    //进行判断map 和实体bean 是否为空,有map可以免去class,但不能全空
    if(map != null){
    title = new String[map.size()];
    Set<String> keys = map.keySet();
    int i = 0;
    for(String key : keys){
    title[i++] = key;
    }

    }else if(clazz != null){
    //获取实体类
    Class demo = Class.forName(clazz.getName());
    //获取实体类属性
    Field[] field = demo.getDeclaredFields();
    title = new String[field.length];
    for(int i=0;i<field.length;i++){
    title[i] = field[i].getName();
    }
    }else{
    throw new Exception("错误!");
    }

    //将list转换json数据
    JSONArray json = JSONArray.fromObject(list);
    //判断是否传入map
    if(map == null){
    //循环title将实体类属性添加到首行
    for(int i=0;i<title.length;i++){
    Label label = new Label(i,0,title[i]);
    sheet.addCell(label);
    }
    }else{
    //循环title将map的value添加到首行
    for(int i=0;i<title.length;i++){
    Label label = new Label(i,0,map.get(title[i]));
    sheet.addCell(label);
    }
    }
    //添加除首行外的其他数据
    for(int i=0;i<json.size();i++){
    for(int j=0;j<title.length;j++){
    Label label = new Label(j,i+1,json.getJSONObject(i).getString(title[j]));
    sheet.addCell(label);
    }
    }
    wb.write();
    wb.close();
    os.close();
    }