一.添加导出工具类

/** 
 * Project Name:vphotoSaaS 
 * File Name:ExcelDownloadUtil.java 
 * Package Name:com.v.photos.action 
 * Date:2016年8月26日上午11:10:32 
 * Copyright (c) 2016, VPhoto All Rights Reserved. 
 * 
 */  
package com.v.photos.action;

import com.v.photos.services.core.ErrorCode;
import com.v.photos.services.core.NestedRuntimeException;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.MapUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author scy
 *
 */
public class ExcelDownloadUtil {


   public static void downloadUtil(HttpServletResponse response,String excelName,LinkedHashMap<String,String> columnMap,Collection dataList){
      downloadUtil(response, excelName, columnMap, dataList,null,null);
   }

   public static void downloadUtil(HttpServletResponse response,String excelName,LinkedHashMap<String,String> columnMap,Collection dataList,Map<String,String> dictMap,Map<String,String> nullDefault){
      downloadUtil(response, excelName, columnMap, dataList, dictMap, nullDefault, null);
   }

   public static void downloadUtil(HttpServletResponse response, String excelName, LinkedHashMap<String,String> columnMap, Collection dataList, Map<String,String> dictMap, Map<String,String> nullDefault, Map<Integer, Colour> colourMap){
      try{
         OutputStream os = response.getOutputStream(); // 取得输出流
         response.reset(); // 清空输出流
         response.setCharacterEncoding("UTF-8");
         response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(excelName+".xls", "UTF-8")); // 设定输出文件头
         response.setContentType("application/msexcel"); // 定义输出类型
         getOutputStream(os, columnMap, dataList, dictMap, nullDefault, colourMap);
         os.close();
      }catch(Exception e){
         e.printStackTrace();
         throw new NestedRuntimeException(ErrorCode.ACTION_FILE_DOWNLOAD_ERROR);          
      }
   }

   public static void getOutputStream(OutputStream os, LinkedHashMap<String,String> columnMap, Collection dataList, Map<String,String> dictMap, Map<String,String> nullDefault, Map<Integer, Colour> colourMap) throws Exception{
      String[] titles = new String[columnMap.size()];
      String[] columns = new String[columnMap.size()];

      SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      DecimalFormat decimal = new DecimalFormat("0.00");
      int f = 0;
      for (Entry<String,String> entry : columnMap.entrySet()) {
         titles[f] = entry.getValue();
         columns[f] = entry.getKey();
         f++;
      }

      WritableWorkbook workbook = Workbook.createWorkbook(os);
      WritableSheet wsheet = workbook.createSheet("sheet1", 0);
      WritableFont font = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false,
            jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
      WritableCellFormat format = new WritableCellFormat(font);
      for (int i = 0; i < titles.length; i++) {
         Label wlabel1 = new Label(i, 0, String.valueOf(titles[i]), format); // 行、列、单元格中的文本、文本格式
         wsheet.addCell(wlabel1);
      }
      font = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false,
            jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
      format = new WritableCellFormat(font);

      for (int i = 0; i < titles.length; i++) {
         wsheet.setColumnView(i, 25);// 设置宽度             
      }

      WritableCellFormat bgYellowFormat = new WritableCellFormat(font);
      bgYellowFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
      bgYellowFormat.setBackground(Colour.YELLOW);

      WritableCellFormat defaultFormat = format;

      f = 1;
      Integer index;
      for (Object obj : dataList) {
         for (int i = 0; i < columns.length; i++) {
            String columnName = columns[i];
            try{
               Object val = null;
               if(obj instanceof Map){
                  Map objMap = (Map) obj;
                  val = objMap.get(columnName);

                  index = MapUtils.getInteger(objMap, "index");
                  if (index != null && index % 2 == 0) {
                     defaultFormat = bgYellowFormat;
                  } else {
                     defaultFormat = format;
                  }

                  if (MapUtils.isNotEmpty(colourMap)) {
                     Colour colour = colourMap.get(f-1);
                     if (colour != null) {
                        WritableCellFormat colourFormat = new WritableCellFormat(font);
                        colourFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
                        colourFormat.setBackground(colour);
                        defaultFormat = colourFormat;
                     }
                  }

               }else{
                  val = PropertyUtils.getNestedProperty(obj, columnName);
               }

               if(val != null){
                  if(dictMap!=null && dictMap.containsKey(columnName+"_"+val)){
                     val = dictMap.get(columnName+"_"+val);
                  }
               }else{
                  if(nullDefault!=null && nullDefault.containsKey(columnName)){
                     val = nullDefault.get(columnName);
                  }
               }

               if(val!=null && val instanceof Number){
                  jxl.write.Number test = new jxl.write.Number(i, f, val == null ? 0 : ((Number) val).doubleValue(), defaultFormat);
                  wsheet.addCell(test);
               }else{
                  if (val!=null && val instanceof Date) {
                     Date date = (Date) val;
                     val = df.format(date);
                  }else if (val!=null && val instanceof Double){
                     val = decimal.format(val);
                  }
                  Label wlabel1 = new Label(i, f, val==null?"":val.toString(), defaultFormat);
                  wsheet.addCell(wlabel1);
               }
            }catch(Exception e){
               e.printStackTrace();
            }
         }
         f++;
      }
      workbook.write(); // 写入文件
      workbook.close();
   }

}

 

二.controller层
/***
* 导出返佣日志信息,前端传ExportType=1,2,3
*或者直接写一个方法,只导出一种类型
* @param response
* @param record
* @return
*/

/***
   * 导出返佣日志信息
   * @param response
   * @param record
   * @return
   */
  public void exportRebateLog(HttpServletResponse response, VBackLog record) {
      /*
   1:导出返佣日志列表
   2:导出返佣日志明细
   3:导出商品返佣明细
  */
      if (record.getExportType() != null && record.getExportType() > 0) {
          if (VBackLog.ExportTypeEnum.VBACKLOG.getId().equals(record.getExportType())) {
              iBackService.exportRebateLog(record, response);
          } else if (VBackLog.ExportTypeEnum.VBACKLOGDETAIL.getId().equals(record.getExportType())) {
              iBackService.exportRebateLogDetail(record, response);
          } else if (VBackLog.ExportTypeEnum.VBACKLOGORDERDETAIL.getId().equals(record.getExportType())) {
              iBackService.exportRebateLogOrderDetail(record, response);
          }
      }
  }

三.service层

/**
 * 导出返佣日志信息
 * @param response
 * @param record
 * @return
 */
void exportRebateLog(VBackLog record, HttpServletResponse response);

/**
 * 导出返佣日志明细信息
 * @param response
 * @param record
 * @return
 */
void exportRebateLogDetail(VBackLog record, HttpServletResponse response);

/**
 * 导出返佣日志商品信息
 * @param response
 * @param record
 * @return
 */
void exportRebateLogOrderDetail(VBackLog record, HttpServletResponse response);

四.serviceImpl层

/**
* 导出返佣日志信息
* 根据sql查询出来的去导出
*/
@Override
public void exportRebateLog(VBackLog record,HttpServletResponse response){
    LinkedHashMap<String, String> columnMap = new LinkedHashMap<>();
    columnMap.put("id", "ID");
    columnMap.put("waterNo", "批量操作号");
    columnMap.put("topUpCount", "涉及充值流水记录数");
    columnMap.put("customerName", "客户名称");
    columnMap.put("backType", "返佣类型");
    columnMap.put("month", "月季");
    columnMap.put("season", "季份");
    columnMap.put("year", "年份");
    columnMap.put("remark", "返佣说明");
    columnMap.put("topUpAmount", "充值金额");
    columnMap.put("backLevel", "返佣档位");
    columnMap.put("paymentTypeId", "用户结款类型");
    columnMap.put("rate", "返佣比例");
    columnMap.put("totalMoney", "本次返佣金额");
    columnMap.put("expenseId", "对应账户中心流水Id");
    columnMap.put("crDate", "创建时间");
    List<Map<String, Object>> dataList = new ArrayList<>();

    //查出返佣日志
    List<VBackLog> vBackLogList = findByVBackLog(record);
    if(CollectionUtils.isEmpty(vBackLogList)){
        throw new NestedRuntimeException(ErrorCode.VBACKLOG_ERROR, "返佣日志查询结果为空,无法导出,请核对查询条件是否有效");
    }
    for(VBackLog vBackLog:vBackLogList){
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("id",vBackLog.getId());
        dataMap.put("waterNo", vBackLog.getWaterNo());
        dataMap.put("topUpCount", vBackLog.getTopUpCount());
        dataMap.put("customerName", vBackLog.getCustomerName());
        dataMap.put("backType", vBackLog.getBackType());
        dataMap.put("month", vBackLog.getMonth());
        dataMap.put("season", vBackLog.getSeason());
        dataMap.put("year", vBackLog.getYear());
        dataMap.put("remark", vBackLog.getRemark());
        dataMap.put("topUpAmount", vBackLog.getTopUpAmount());
        dataMap.put("backLevel", vBackLog.getBackLevel());
        dataMap.put("paymentTypeId", vBackLog.getPaymentTypeId());
        dataMap.put("rate", vBackLog.getRate());
        dataMap.put("totalMoney", vBackLog.getTopUpAmount());
        dataMap.put("expenseId", vBackLog.getExpenseId());
        dataMap.put("crDate", vBackLog.getCrDate());
        dataList.add(dataMap);
    }
    System.out.println("返佣日志列表111111111111111111111111111111"+dataList);
    ExcelDownloadUtil.downloadUtil(response, "返佣日志列表", columnMap, dataList);
}

/**导出返佣日志明细信息*/
@Override
public void exportRebateLogDetail(VBackLog record,HttpServletResponse response){
    LinkedHashMap<String, String> columnMap = new LinkedHashMap<>();
    columnMap.put("id", "ID");
    columnMap.put("waterNo", "批量操作号");
    columnMap.put("crmOrderNo", "相关CRM订单");
    columnMap.put("orderNo", "后台订单号");
    columnMap.put("customerName", "客户名称");
    columnMap.put("backType", "返佣类型");
    columnMap.put("month", "月季");
    columnMap.put("season", "季份");
    columnMap.put("year", "年份");
    columnMap.put("remark", "返佣说明");
    columnMap.put("orderAmount", "订单总金额");
    columnMap.put("returnUserName", "回款人");
    columnMap.put("backLevel", "本次返佣档位");
    columnMap.put("paymentTypeId", "用户结款类型");
    columnMap.put("backRate", "返佣比例");
    columnMap.put("backAmount", "本次返佣金额");
    columnMap.put("crDate", "创建时间");
    columnMap.put("BackLogOrderItemDetail", "返佣商品");
    List<Map<String, Object>> dataList = new ArrayList<>();

    //查出返佣日志
    List<VBackLog> byVBackLog = findByVBackLog(record);
    if(CollectionUtils.isEmpty(byVBackLog)){
        throw new NestedRuntimeException(ErrorCode.VBACKLOG_ERROR, "返佣日志查询结果为空,无法导出,请核对查询条件是否有效");
    }
    for(VBackLog vBackLog:byVBackLog){
        //查出返佣日志详情
        List<VBackLogOrderDetail> byWaterNo = findByWaterNo(vBackLog.getWaterNo());
        if(CollectionUtils.isEmpty(byWaterNo)){
            throw new NestedRuntimeException(ErrorCode.VBACKLOG_DETAIL_ERROR, "返佣日志详情查询结果为空,无法导出,请核对查询条件是否有效");
        }
        for(VBackLogOrderDetail vBackLogOrderDetail:byWaterNo){
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("id", vBackLogOrderDetail.getId());
            dataMap.put("waterNo",vBackLogOrderDetail.getWaterNo() );
            dataMap.put("crmOrderNo",vBackLogOrderDetail.getCrmOrderNo());
            dataMap.put("orderNo",vBackLogOrderDetail.getOrderNo() );
            dataMap.put("customerName",vBackLogOrderDetail.getCustomerName() );
            dataMap.put("backType",vBackLogOrderDetail.getBackType() );
            dataMap.put("month",vBackLogOrderDetail.getMonth() );
            dataMap.put("season",vBackLogOrderDetail.getSeason() );
            dataMap.put("year",vBackLogOrderDetail.getYear() );
            dataMap.put("remark",vBackLogOrderDetail.getRemark() );
            dataMap.put("orderAmount",vBackLogOrderDetail.getOrderAmount());
            dataMap.put("returnUserName",vBackLogOrderDetail.getReturnUserName() );
            dataMap.put("backLevel",vBackLogOrderDetail.getBackLevel() );
            dataMap.put("paymentTypeId",vBackLogOrderDetail.getPaymentTypeId() );
            dataMap.put("backRate",vBackLogOrderDetail.getBackRate() );
            dataMap.put("backAmount",vBackLogOrderDetail.getBackAmount() );
            dataMap.put("crDate",vBackLogOrderDetail.getCrDate() );
            //获取返佣商品明细
            List<VBackLogOrderItemDetail> vBackLogOrderItemDetails = vBackLogOrderDetail.getvBackLogOrderItemDetail();
            if(CollectionUtils.isNotEmpty(vBackLogOrderItemDetails)){
                StringBuilder builder = new StringBuilder();
                for(VBackLogOrderItemDetail vBackLogOrderItemDetail : vBackLogOrderItemDetails){
                    builder.append(org.apache.commons.lang3.StringUtils.isNotBlank(vBackLogOrderItemDetail.getGoodsNo()) ? vBackLogOrderItemDetail.getGoodsNo()+"," : org.apache.commons.lang3.StringUtils.EMPTY);
                    builder.append(org.apache.commons.lang3.StringUtils.isNotBlank(vBackLogOrderItemDetail.getGoodsName()) ? vBackLogOrderItemDetail.getGoodsName()+"," : org.apache.commons.lang3.StringUtils.EMPTY);
                    builder.append(Objects.nonNull(vBackLogOrderItemDetail.getBackAmount()) ? vBackLogOrderItemDetail.getBackAmount().toString()+"," : org.apache.commons.lang3.StringUtils.EMPTY);
                    builder.append("\n");
                }
                dataMap.put("BackLogOrderItemDetail", builder.toString());
            }else{
                dataMap.put("BackLogOrderItemDetail", org.apache.commons.lang3.StringUtils.EMPTY);
            }
            dataList.add(dataMap);
        }
    }


    System.out.println("返佣日志明细列表111111111111111111111111111111"+dataList);
    ExcelDownloadUtil.downloadUtil(response, "返佣日志明细列表", columnMap, dataList);
}

/**导出商品返佣明细*/
@Override
public void exportRebateLogOrderDetail(VBackLog record,HttpServletResponse response){
    LinkedHashMap<String, String> columnMap = new LinkedHashMap<>();
    columnMap.put("id", "ID");
    columnMap.put("waterNo", "批量操作号");
    columnMap.put("customerName", "客户名称");
    columnMap.put("orderNo", "后台订单号");
    columnMap.put("crmOrderNo", "相关CRM订单");
    columnMap.put("backType", "返佣类型");
    columnMap.put("season", "季份");
    columnMap.put("remark", "返佣说明");
    columnMap.put("goodsNo", "商品编号");
    columnMap.put("goodsName", "商品名称");
    columnMap.put("basePrice", "基础单价");
    columnMap.put("quantity", "数量");
    columnMap.put("paidPrice", "售卖单价");
    columnMap.put("paidTotalPrice", "商品售卖总计");
    columnMap.put("cashPaidAmount", "现金账户支付部分");
    columnMap.put("canBack", "参与返佣");
    columnMap.put("backAmount", "本次返佣金额");
    columnMap.put("crDate", "创建时间");
    List<Map<String, Object>> dataList = new ArrayList<>();

    //查出返佣日志
    List<VBackLog> byVBackLog = findByVBackLog(record);
    if(CollectionUtils.isEmpty(byVBackLog)){
        throw new NestedRuntimeException(ErrorCode.VBACKLOG_ERROR, "返佣日志查询结果为空,无法导出,请核对查询条件是否有效");
    }
    for(VBackLog vBackLog:byVBackLog){
        //查出返佣日志详情
        List<VBackLogOrderDetail> byWaterNo = findByWaterNo(vBackLog.getWaterNo());
        if(CollectionUtils.isEmpty(byWaterNo)){
            throw new NestedRuntimeException(ErrorCode.VBACKLOG_DETAIL_ERROR, "返佣日志详情查询结果为空,无法导出,请核对查询条件是否有效");
        }
        for(VBackLogOrderDetail vBackLogOrderDetail:byWaterNo){
            //查询返佣商品明细
            List<VBackLogOrderItemDetail> vBackLogOrderItemDetails=findByOrderId(vBackLogOrderDetail.getOrderId());
            if(CollectionUtils.isEmpty(vBackLogOrderItemDetails)){
                throw new NestedRuntimeException(ErrorCode.VBACKLOG_ORDER_ERROR, "返佣商品查询结果为空,无法导出,请核对查询条件是否有效");
            }
            for(VBackLogOrderItemDetail vBackLogOrderItemDetail : vBackLogOrderItemDetails){
                Map<String,Object> dataMap=new HashMap<>();
                dataMap.put("id",vBackLogOrderDetail.getId());
                dataMap.put("waterNo",vBackLogOrderDetail.getWaterNo() );
                dataMap.put("customerName",vBackLogOrderDetail.getCustomerName() );
                dataMap.put("orderNo",vBackLogOrderDetail.getOrderNo() );
                dataMap.put("crmOrderNo",vBackLogOrderDetail.getCrmOrderNo());
                dataMap.put("backType", vBackLogOrderDetail.getBackType());
                dataMap.put("season", vBackLogOrderDetail.getSeason());
                dataMap.put("remark", vBackLogOrderDetail.getRemark());
                dataMap.put("goodsNo", vBackLogOrderItemDetail.getGoodsNo());
                dataMap.put("goodsName",vBackLogOrderItemDetail.getGoodsName());
                dataMap.put("basePrice", vBackLogOrderItemDetail.getBasePrice());
                dataMap.put("quantity", vBackLogOrderItemDetail.getQuantity());
                dataMap.put("paidPrice", vBackLogOrderItemDetail.getPaidPrice());
                dataMap.put("paidTotalPrice", vBackLogOrderItemDetail.getPaidTotalPrice());
                dataMap.put("cashPaidAmount", vBackLogOrderItemDetail.getCashPaidAmount());
                dataMap.put("canBack", vBackLogOrderItemDetail.getCanBack());
                dataMap.put("backAmount", vBackLogOrderItemDetail.getBackAmount());
                dataMap.put("crDate", vBackLogOrderItemDetail.getCrDate());
                dataList.add(dataMap);
            }
        }
    }
    System.out.println("商品返佣列表111111111111111111111111111111"+dataList);
    ExcelDownloadUtil.downloadUtil(response, "商品返佣列表", columnMap, dataList);
}

ExcelDownloadUtil.downloadUtil(response, "返佣日志列表", columnMap, dataList);

columnMap是导出的头上的第一行名字。
dataList是查出的数据。