非常好用的导出生成EXCEL表格。


工具类:

第一个生成指定位置

package com.wolita.ywdb.common.utils.excel;



import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


import org.apache.commons.lang.StringUtils;


public class ExcelXlsx {


public String filePath(String paper){
if(StringUtils.isBlank(paper)){
paper = "allOrder";
}
File file = new File("D:\\"+paper);
if(!file.exists() && !file.isDirectory()){
file.mkdir();
}
//String path = file+"\\"+UUID.randomUUID().toString().replace("-", "")+".xlsx";
String path = file+"\\"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".xlsx";
return path;
}

}



真正的工具类,将FORM表单的TABLE的数据导出生成EXCEL文档

/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.wolita.ywdb.common.utils.excel;


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletResponse;


import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.google.common.collect.Lists;
import com.wolita.ywdb.common.utils.Encodes;
import com.wolita.ywdb.common.utils.Reflections;
import com.wolita.ywdb.common.utils.excel.annotation.ExcelField;
import com.wolita.ywdb.modules.sys.utils.DictUtils;


/**
 * 导出Excel文件(导出“XLSX”格式,支持大数据量导出   @see org.apache.poi.ss.SpreadsheetVersion)
 * @author ThinkGem
 * @version 2013-04-21
 */
public class ExportExcel {

private static Logger log = LoggerFactory.getLogger(ExportExcel.class);

/**
* 工作薄对象
*/
private SXSSFWorkbook wb;

/**
* 工作表对象
*/
private Sheet sheet;

/**
* 样式列表
*/
private Map<String, CellStyle> styles;

/**
* 当前行号
*/
private int rownum;

/**
* 注解列表(Object[]{ ExcelField, Field/Method })
*/
List<Object[]> annotationList = Lists.newArrayList();

/**
* 构造函数
* @param title 表格标题,传“空值”,表示无标题
* @param cls 实体对象,通过annotation.ExportField获取标题
*/
public ExportExcel(String title, Class<?> cls){
this(title, cls, 1);
}

/**
* 构造函数
* @param title 表格标题,传“空值”,表示无标题
* @param cls 实体对象,通过annotation.ExportField获取标题
* @param type 导出类型(1:导出数据;2:导出模板)
* @param groups 导入分组
*/
public ExportExcel(String title, Class<?> cls, int type, int... groups){
// Get annotation field 
Field[] fs = cls.getDeclaredFields();
for (Field f : fs){
ExcelField ef = f.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==type)){
if (groups!=null && groups.length>0){
boolean inGroup = false;
for (int g : groups){
if (inGroup){
break;
}
for (int efg : ef.groups()){
if (g == efg){
inGroup = true;
annotationList.add(new Object[]{ef, f});
break;
}
}
}
}else{
annotationList.add(new Object[]{ef, f});
}
}
}
// Get annotation method
Method[] ms = cls.getDeclaredMethods();
for (Method m : ms){
ExcelField ef = m.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==type)){
if (groups!=null && groups.length>0){
boolean inGroup = false;
for (int g : groups){
if (inGroup){
break;
}
for (int efg : ef.groups()){
if (g == efg){
inGroup = true;
annotationList.add(new Object[]{ef, m});
break;
}
}
}
}else{
annotationList.add(new Object[]{ef, m});
}
}
}
// Field sorting
Collections.sort(annotationList, new Comparator<Object[]>() {
public int compare(Object[] o1, Object[] o2) {
return new Integer(((ExcelField)o1[0]).sort()).compareTo(
new Integer(((ExcelField)o2[0]).sort()));
};
});
// Initialize
List<String> headerList = Lists.newArrayList();
for (Object[] os : annotationList){
String t = ((ExcelField)os[0]).title();
// 如果是导出,则去掉注释
if (type==1){
String[] ss = StringUtils.split(t, "**", 2);
if (ss.length==2){
t = ss[0];
}
}
headerList.add(t);
}
initialize(title, headerList);
}

/**
* 构造函数
* @param title 表格标题,传“空值”,表示无标题
* @param headers 表头数组
*/
public ExportExcel(String title, String[] headers) {
initialize(title, Lists.newArrayList(headers));
}

/**
* 构造函数
* @param title 表格标题,传“空值”,表示无标题
* @param headerList 表头列表
*/
public ExportExcel(String title, List<String> headerList) {
initialize(title, headerList);
}

/**
* 初始化函数
* @param title 表格标题,传“空值”,表示无标题
* @param headerList 表头列表
*/
private void initialize(String title, List<String> headerList) {
this.wb = new SXSSFWorkbook(500);
this.sheet = wb.createSheet("Export");
this.styles = createStyles(wb);
// Create title
if (StringUtils.isNotBlank(title)){
Row titleRow = sheet.createRow(rownum++);
titleRow.setHeightInPoints(30);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellStyle(styles.get("title"));
titleCell.setCellValue(title);
sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1));
}
// Create header
if (headerList == null){
throw new RuntimeException("headerList not null!");
}
Row headerRow = sheet.createRow(rownum++);
headerRow.setHeightInPoints(16);
for (int i = 0; i < headerList.size(); i++) {
Cell cell = headerRow.createCell(i);
cell.setCellStyle(styles.get("header"));
String[] ss = StringUtils.split(headerList.get(i), "**", 2);
if (ss.length==2){
cell.setCellValue(ss[0]);
Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
comment.setString(new XSSFRichTextString(ss[1]));
cell.setCellComment(comment);
}else{
cell.setCellValue(headerList.get(i));
}
sheet.autoSizeColumn(i);
}
for (int i = 0; i < headerList.size(); i++) {  
int colWidth = sheet.getColumnWidth(i)*2;
        sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);  
}
log.debug("Initialize success.");
}

/**
* 创建表格样式
* @param wb 工作薄对象
* @return 样式列表
*/
private Map<String, CellStyle> createStyles(Workbook wb) {
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();

CellStyle style = wb.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
Font titleFont = wb.createFont();
titleFont.setFontName("Arial");
titleFont.setFontHeightInPoints((short) 16);
titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(titleFont);
styles.put("title", style);


style = wb.createCellStyle();
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
Font dataFont = wb.createFont();
dataFont.setFontName("Arial");
dataFont.setFontHeightInPoints((short) 10);
style.setFont(dataFont);
styles.put("data", style);

style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(CellStyle.ALIGN_LEFT);
styles.put("data1", style);


style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(CellStyle.ALIGN_CENTER);
styles.put("data2", style);


style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(CellStyle.ALIGN_RIGHT);
styles.put("data3", style);

style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
// style.setWrapText(true);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
Font headerFont = wb.createFont();
headerFont.setFontName("Arial");
headerFont.setFontHeightInPoints((short) 10);
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
headerFont.setColor(IndexedColors.WHITE.getIndex());
style.setFont(headerFont);
styles.put("header", style);

return styles;
}


/**
* 添加一行
* @return 行对象
*/
public Row addRow(){
return sheet.createRow(rownum++);
}



/**
* 添加一个单元格
* @param row 添加的行
* @param column 添加列号
* @param val 添加值
* @return 单元格对象
*/
public Cell addCell(Row row, int column, Object val){
return this.addCell(row, column, val, 0, Class.class);
}

/**
* 添加一个单元格
* @param row 添加的行
* @param column 添加列号
* @param val 添加值
* @param align 对齐方式(1:靠左;2:居中;3:靠右)
* @return 单元格对象
*/
public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType){
Cell cell = row.createCell(column);
String cellFormatString = "@";
try {
if(val == null){
cell.setCellValue("");
}else if(fieldType != Class.class){
cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val));
}else{
if(val instanceof String) {
cell.setCellValue((String) val);
}else if(val instanceof Integer) {
cell.setCellValue((Integer) val);
cellFormatString = "0";
}else if(val instanceof Long) {
cell.setCellValue((Long) val);
cellFormatString = "0";
}else if(val instanceof Double) {
cell.setCellValue((Double) val);
cellFormatString = "0.00";
}else if(val instanceof Float) {
cell.setCellValue((Float) val);
cellFormatString = "0.00";
}else if(val instanceof Date) {
cell.setCellValue((Date) val);
cellFormatString = "yyyy-MM-dd HH:mm";
}else {
cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(), 
"fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val));
}
}
if (val != null){
CellStyle style = styles.get("data_column_"+column);
if (style == null){
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"+(align>=1&&align<=3?align:"")));
        style.setDataFormat(wb.createDataFormat().getFormat(cellFormatString));
styles.put("data_column_" + column, style);
}
cell.setCellStyle(style);
}
} catch (Exception ex) {
log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString());
cell.setCellValue(val.toString());
}
return cell;
}


/**
* 添加数据(通过annotation.ExportField添加数据)
* @return list 数据列表
*/
public <E> ExportExcel setDataList(List<E> list){
for (E e : list){
int colunm = 0;
Row row = this.addRow();
StringBuilder sb = new StringBuilder();
for (Object[] os : annotationList){
ExcelField ef = (ExcelField)os[0];
Object val = null;
// Get entity value
try{
if (StringUtils.isNotBlank(ef.value())){
val = Reflections.invokeGetter(e, ef.value());
}else{
if (os[1] instanceof Field){
val = Reflections.invokeGetter(e, ((Field)os[1]).getName());
}else if (os[1] instanceof Method){
val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {});
}
}
// If is dict, get dict label
if (StringUtils.isNotBlank(ef.dictType())){
val = DictUtils.getDictLabel(val==null?"":val.toString(), ef.dictType(), "");
}
}catch(Exception ex) {
// Failure to ignore
log.info(ex.toString());
val = "";
}
this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
sb.append(val + ", ");
}
log.debug("Write success: ["+row.getRowNum()+"] "+sb.toString());
}
return this;
}

/**
* 输出数据流
* @param os 输出数据流
*/
public ExportExcel write(OutputStream os) throws IOException{
wb.write(os);
return this;
}

/**
* 输出到客户端
* @param fileName 输出文件名
*/
public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
write(response.getOutputStream());
return this;
}

/**
* 输出到文件
* @param fileName 输出文件名
*/
public ExportExcel writeFile(String name) throws FileNotFoundException, IOException{
FileOutputStream os = new FileOutputStream(name);
this.write(os);
return this;
}

/**
* 清理临时文件
*/
public ExportExcel dispose(){
wb.dispose();
return this;
}

// /**
// * 导出测试
// */
// public static void main(String[] args) throws Throwable {
//
// List<String> headerList = Lists.newArrayList();
// for (int i = 1; i <= 10; i++) {
// headerList.add("表头"+i);
// }
//
// List<String> dataRowList = Lists.newArrayList();
// for (int i = 1; i <= headerList.size(); i++) {
// dataRowList.add("数据"+i);
// }
//
// List<List<String>> dataList = Lists.newArrayList();
// for (int i = 1; i <=1000000; i++) {
// dataList.add(dataRowList);
// }
//
// ExportExcel ee = new ExportExcel("表格标题", headerList);
//
// for (int i = 0; i < dataList.size(); i++) {
// Row row = ee.addRow();
// for (int j = 0; j < dataList.get(i).size(); j++) {
// ee.addCell(row, j, dataList.get(i).get(j));
// }
// }
//
// ee.writeFile("target/export.xlsx");
//
// ee.dispose();
//
// log.debug("Export success.");
//
// }


}

CONTROLLER控制器

//生成Excel表单
@RequestMapping(value = "exportData")
public void exportData(HttpServletRequest request, HttpServletResponse response,Model model){
try {
// 表格的标题栏
System.out.println(111111);
String[] headers = { "平台订单号", "商户订单号", "银行订单号", "支付通道", "支付类型",
"商户信息", "付款状态", "创建时间", "支付时间", "支付金额", "手续费率" };
List<String> headerList = Lists.newArrayList();
for (int i = 0; i < headers.length; i++) {
headerList.add(headers[i]);
}




String assId = request.getParameter("assId");
String assAccountNum = request.getParameter("assAccountNum");
String assOrderId = request.getParameter("assOrderId");
String orderId = request.getParameter("orderId");
String payStatus = request.getParameter("payStatus");
String paymentType = request.getParameter("paymentType");
String orderType = request.getParameter("orderType");
String channelId = request.getParameter("channelId");
String beginTime = request.getParameter("beginTime");
String endTime = request.getParameter("endTime");
System.out.println(assId);
System.out.println(assAccountNum);
System.out.println(assOrderId);
System.out.println(orderId);
System.out.println(payStatus);
System.out.println(paymentType);
System.out.println(orderType);
System.out.println(channelId);
System.out.println(beginTime);
System.out.println(endTime);



List<ShopOrder> list = shopOrderService.findOrderList(assId,assAccountNum,assOrderId,orderId,payStatus,paymentType,orderType,channelId,beginTime,endTime);


List<List<String>> dataList = Lists.newArrayList();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int r = 0; r < list.size(); r++) {
List<String> dataRowList = Lists.newArrayList();
Date date;
dataRowList.add(list.get(r).getOrderId());
dataRowList.add(list.get(r).getAssOrderId());
dataRowList.add(list.get(r).getPtOrderId());
dataRowList.add(String.valueOf(list.get(r).getChannelId()));
dataRowList.add(list.get(r).getPaymentType());
dataRowList.add(list.get(r).getAssAccountName() + "[" + list.get(r).getAssAccountNum()+"]");
dataRowList.add(GjPayStatus.getLabelMap().get(list.get(r).getPayStatus()));
dataRowList.add(sdf.format(list.get(r).getCreateDate()));
date = list.get(r).getPaymentTime();
if(date == null){
dataRowList.add("");
}else{
dataRowList.add(sdf.format(list.get(r).getPaymentTime()));
}
dataRowList.add(String.valueOf(list.get(r).getPayMoney()));
dataRowList.add(String.valueOf(list.get(r).getDiscount()));
dataList.add(dataRowList);


}




ExportExcel ee = new ExportExcel("订单表", headerList);


for (int i = 0; i < dataList.size(); i++) {
Row row = ee.addRow();
for (int j = 0; j < dataList.get(i).size(); j++) {
ee.addCell(row, j, dataList.get(i).get(j));
}
}
ExcelXlsx excelxlsx = new ExcelXlsx();
ee.writeFile(excelxlsx.filePath(assId));


ee.dispose();
Logger log = LoggerFactory.getLogger(ExportExcel.class);
log.debug("Export success.");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}



XML的SQL语句查询:

<select id="findOrderList" resultType="ShopOrder">
SELECT
a.order_id AS orderId,
a.ass_order_id AS assOrderId,
a.pt_order_id as ptOrderId,
a.channel_id as channelId,
            a.payment_type AS paymentType,
            b.ass_name as assAccountName,
            b.ass_id as assAccountNum,
a.pay_status AS payStatus,
a.create_date AS createDate,
a.payment_time AS paymentTime,
a.pay_money AS payMoney,
a.discount AS discount
FROM shop_order a left join shop_ass b on a.ass_id = b.id
<where>
<if test="assId != null and assId != ''">
AND a.ass_id = #{assId}
</if>
<if test="assAccountNum != null and assAccountNum != ''">
AND b.ass_id like CONCAT('%', #{assAccountNum}, '%')
</if>
<if test="assOrderId != null and assOrderId != ''">
AND a.ASS_ORDER_ID like CONCAT('%', #{assOrderId}, '%')
</if>


<if test="orderId != null and orderId != ''">
AND a.order_id like CONCAT('%', #{orderId}, '%')
</if>

<if test="payStatus != null and payStatus != ''">
AND a.pay_status = #{payStatus}
</if>

<if test="paymentType != null and paymentType != ''">
AND a.payment_type = #{paymentType}
</if>

<if test="orderType != null and orderType != ''">
AND a.order_type = #{orderType}
</if>


<if test="channelId != null and channelId != ''">
AND a.channel_id = #{channelId}
</if>
<if test="beginTime != null and beginTime != '' and endTime != null and endTime != ''">
AND a.create_date between #{beginTime} and #{endTime}
</if>
</where>
</select>


JSP页面的JS实现

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<title>订单信息管理</title>
<meta name="decorator" content="default"/>
<script type="text/javascript">
$(document).ready(function() {
$("#btnSubmitExcel").click(function(){
var assId = $("#assId").val();
var assAccountNum = $("#assAccountNum").val();
var assOrderId = $("#assOrderId").val();
var orderId = $("#orderId").val();
var payStatus = $("#payStatus").val();
var paymentType = $("#paymentType").val();
var orderType = $("#orderType").val();
var channelId = $("#channelId").val();
var beginTime = $("#beginTime").val();
var endTime = $("#endTime").val();


$.ajax({
  type:"get",//get/post类型
  url:"${ctx}/order/shopOrder/exportData",//接口或者静态文件
  data:{"assId":assId,"assAccountNum":assAccountNum,"assOrderId":assOrderId,"orderId":orderId,"payStatus":payStatus,"paymentType":paymentType,"orderType":orderType,"channelId":channelId,"beginTime":beginTime,"endTime":endTime},
   success:function(data){
                //成功返回的数据data
                $("#contentTable").html(data);
                document.getElementById("searchForm").action='${ctx}/order/shopOrder';
                document.getElementById("searchForm").submit();


                },
     error:function(e){


         console.log(e)


     }
  });
});
});
function page(n,s){
$("#pageNo").val(n);
$("#pageSize").val(s);
$("#searchForm").submit();
        return false;
        }
function searchToday(type){
$("#reportType").val(type);
$("#searchForm").submit();
}

//重置查询条件
function formReset() {  
        $(':input','#searchForm')  
         .not(':button, :submit, :reset, :hidden')  
         .val('')  
         .removeAttr('checked')  
         .removeAttr('selected');                    
    }  
/* function clear(){
$("#searchForm").reset() ;
alert("aaa");
        } */
</script>
</head>
<body>
<ul class="nav nav-tabs">
<li class="active"><a href="${ctx}/order/shopOrder/">订单信息列表</a></li>
<shiro:hasPermission name="order:shopOrder:edit"><li><a href="${ctx}/order/shopOrder/form">订单信息添加</a></li></shiro:hasPermission>
</ul>
<form:form id="searchForm" modelAttribute="shopOrder" action="${ctx}/order/shopOrder/" method="post" class="breadcrumb form-search">
<input type="hidden" value="" id="reportType" name="reportType"/>
<input id="pageNo" name="pageNo" type="hidden" value="${page.pageNo}"/>
<input id="pageSize" name="pageSize" type="hidden" value="${page.pageSize}"/>
<ul class="ul-form">
<li><label>商家商户号:</label>
<form:input id="assAccountNum" path="assAccountNum" htmlEscape="false" class="input-medium"/>
</li>


<li><label>平台订单号:</label>
<form:input id="orderId" path="orderId" htmlEscape="false" class="input-medium"/>
</li>
<li>
<label>商户订单号:</label>
<form:input id="assOrderId" path="assOrderId" htmlEscape="false"  class="input-medium"/>
</li>
<li>
<label>三方订单号:</label>
<form:input id="ptOrderId" path="ptOrderId" htmlEscape="false"  class="input-medium"/>
</li>


<li><label>从:</label>
<input id="beginTime" name="beginTime" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate"
value="${shopOrder.beginTime}"
οnclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});"/>


</li>
<li><label>到:</label>
<input id="endTime" name="endTime" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate"
value="${shopOrder.endTime}"
οnclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});"/>
</li>


<li><label>付款状态:</label>
<form:select id="payStatus" path="payStatus" class="input-xlarge" style="width:150px;">
<form:option value="" label="全部付款状态"/>
<form:options items="${payStatusList}"  htmlEscape="false"/>
</form:select>
</li>
<li><label>支付类型:</label>
<form:select id="paymentType" path="paymentType" class="input-xlarge" style="width:160px;">
<form:option value="" label="全部支付类型"/>
<form:options items="${payTypes}"  htmlEscape="false"/>
</form:select>
</li>
<li><label>订单类型:</label>
<form:select id="orderType" path="orderType" class="input-xlarge" style="width:160px;">
<form:option value="" label="全部支订单类型"/>
<form:options items="${orderTypes}"  htmlEscape="false"/>
</form:select>
</li>
<li><label>支付通道:</label>
<select name="channelId" id="channelId" class="input-xlarge">
<option value="">全部支付通道</option>
<c:forEach items="${channels}" var="item">
<option value="${item.id}" <c:if test="${item.id==shopOrder.channelId}"> selected</c:if>> ${item.chanelName}</option>
</c:forEach>
</select>
</li>


<li class="btns"><input id="btnSubmit" class="btn btn-primary" type="submit" value="查询"/></li>
<li class="btns"><input id="todayBtn" class="btn btn-primary" type="button" value="今日" οnclick="searchToday(1)"/></li>
<li class="btns"> <input id="todayBtn" class="btn btn-primary" type="button" value="昨日" οnclick="searchToday(2)"/></li>
<li class="btns"> <input id="todayBtn" class="btn btn-primary" type="button" value="本周" οnclick="searchToday(3)"/></li>
<li class="btns"> <input id="todayBtn" class="btn btn-primary" type="button" value="上周" οnclick="searchToday(4)"/></li>
<li class="btns"><li class="btns"> <input id="todayBtn" class="btn btn-primary" type="button" value="本月" οnclick="searchToday(5)"/></li>
<li class="btns"><input id="todayBtn" class="btn btn-primary" type="button" value="上月" οnclick="searchToday(6)"/></li>

<li class="btns"><input id="btnSubmitExcel" class="btn btn-primary" type="button" value="导出订单查询Excel表单" /></li>
<li class="btns"><input id="btnReset" class="btn btn-primary" type="button" οnclick="formReset()" value="清空查询条件" /></li>

<li class="clearfix"></li>
</ul>
</form:form>
<sys:message content="${message}"/>
<table id="contentTable" class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th colspan="4">
<span style="color:green">
成功交易:
<fmt:formatNumber type="number" value="${orderReport.successTotalPayMoney}" pattern="0.000" maxFractionDigits="3"/>¥,
${orderReport.successTotalPayCount}笔,
手续费[<fmt:formatNumber type="number" value="${orderReport.successTotalRate}" pattern="0.000" maxFractionDigits="3"/>]¥
</span>

</th>
<th colspan="4">
<span style="color:red">
失败交易:
<fmt:formatNumber type="number" value="${orderReport.failedTotalPayMoney}" pattern="0.000" maxFractionDigits="3"/>¥,
${orderReport.failedTotalPayCount}笔,
</span>
</th>


<th colspan="4">
<span style="color:green">
交易金额成功率:<fmt:formatNumber type="number" value="${orderReport.rateMoney}" pattern="0.000" maxFractionDigits="3"/>%
</span>
<span style="color:red">
订单笔数成功率:<fmt:formatNumber type="number" value="${orderReport.rateCount}" pattern="0.000" maxFractionDigits="3"/>%
</span>
</th>
</tr> 
<tr>
<th>平台订单号</th>
<th>商户订单号</th>
<th>银行订单号 </th>
<th>支付通道</th>
<th>支付类型</th>
<th>商户信息</th>
<th>付款状态</th>
<th>创建时间</th>
<th>支付时间</th>
<th>支付金额</th>
<th>手续费率</th>
<!--
<th>订单标题</th>
<th>订单内容</th>
-->
<shiro:hasPermission name="order:shopOrder:edit"><th>操作</th></shiro:hasPermission>
</tr>
</thead>
<tbody>
<c:forEach items="${page.list}" var="shopOrder">
<tr>
<td>
<a href="#">
${shopOrder.orderId}
</a>
</td>
<td>
${shopOrder.assOrderId}
</td>


<td>
${shopOrder.ptOrderId}
</td>
<td>
${shopOrder.channelId}
</td>
<td>
${fns:getDisplayLabel(payTypes,shopOrder.paymentType)}
</td>
<td>
${shopOrder.assAccountName}[${shopOrder.assAccountNum}]
</td>
<td>
<c:if test="${shopOrder.payStatus=='60006'}">
<span style="color:green">
${fns:getDisplayLabel(payStatusList,shopOrder.payStatus)}
</span>
</c:if>
<c:if test="${shopOrder.payStatus=='60001'}">
<span style="color:red">
${fns:getDisplayLabel(payStatusList,shopOrder.payStatus)}
</span>
</c:if>
<c:if test="${shopOrder.payStatus=='60003'}">
<span style="color:red">
${fns:getDisplayLabel(payStatusList,shopOrder.payStatus)}
</span>
</c:if>
</td>
<td>
<fmt:formatDate value="${shopOrder.createDate}" pattern="yyyy-MM-dd HH:mm:ss"/>
</td>
<td>
<fmt:formatDate value="${shopOrder.paymentTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
</td>
<td>
<fmt:formatNumber type="number" value="${shopOrder.payMoney}" pattern="0.000" maxFractionDigits="3"/>
</td>
<td>
${shopOrder.discount}%
</td>
<!--
<td>
${shopOrder.goodsTitle}
</td>
<td>
${shopOrder.goodsDesc}
</td>
-->
<shiro:hasPermission name="order:shopOrder:edit"><td>
<a href="${ctx}/order/shopOrder/notify?id=${shopOrder.id}" οnclick="return confirmx('确认要重新通知该订单吗?', this.href)">补通知</a>
</td></shiro:hasPermission>
</tr>
</c:forEach>
</tbody>
</table>
<div class="pagination">${page}</div>
</body>
</html>

还需要补充一个注解类。在实体类中对属性进行映射

/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.ebank.common.utils.excel.annotation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


/**
 * Excel注解定义
 * @author ThinkGem
 * @version 2013-03-10
 */
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField {


/**
* 导出字段名(默认调用当前字段的“get”方法,如指定导出字段为对象,请填写“对象名.对象属性”,例:“area.name”、“office.name”)
*/
String value() default "";

/**
* 导出字段标题(需要添加批注请用“**”分隔,标题**批注,仅对导出模板有效)
*/
String title();

/**
* 字段类型(0:导出导入;1:仅导出;2:仅导入)
*/
int type() default 0;


/**
* 导出字段对齐方式(0:自动;1:靠左;2:居中;3:靠右)
*/
int align() default 0;

/**
* 导出字段字段排序(升序)
*/
int sort() default 0;


/**
* 如果是字典类型,请设置字典的type值
*/
String dictType() default "";

/**
* 反射类型
*/
Class<?> fieldType() default Class.class;

/**
* 字段归属组(根据分组导出导入)
*/
int[] groups() default {};

}




优化后的控制器 io流输出保存

//生成Excel表单
@RequestMapping(value = "exportData")
public String exportData(ShopPay pay, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes){
try {
String assCode = request.getParameter("assCode");
String assPayOrderNo = request.getParameter("assPayOrderNo");
String sysPayOrderNo = request.getParameter("sysPayOrderNo");
String channelPayOrderNo = request.getParameter("channelPayOrderNo");
String payStatus = request.getParameter("payStatus");
String paymentType = request.getParameter("paymentType");
String channelId = request.getParameter("channelId");
String beginTime = request.getParameter("beginTime");
String endTime = request.getParameter("endTime");
System.out.println("assCode===========:"+assCode);
System.out.println("assPayOrderNo===========:"+assPayOrderNo);
System.out.println("assPayOrderNo===========:"+sysPayOrderNo);
System.out.println("channelPayOrderNo===========:"+channelPayOrderNo);
System.out.println("payStatus===========:"+payStatus);
System.out.println("paymentType===========:"+paymentType);
System.out.println("channelId===========:"+channelId);
System.out.println("beginTime===========:"+beginTime);
System.out.println("endTime===========:"+endTime);
ShopPay shopPay = new ShopPay();
shopPay.setAssCode(assCode);
shopPay.setAssPayOrderNo(assPayOrderNo);
shopPay.setSysPayOrderNo(sysPayOrderNo);
shopPay.setChannelPayOrderNo(channelPayOrderNo);
shopPay.setPayStatus(payStatus);
shopPay.setPaymentType(paymentType);
if(StringUtils.isNotBlank(channelId)) {
shopPay.setChannelId(Long.valueOf(channelId));
}
shopPay.setBeginTime(beginTime);
shopPay.setEndTime(endTime);
List<ShopPay> list = this.payService.findOrderList(shopPay);
String fileName = "订单数据" + DateUtils.getDate("yyyyMMddHHmmss")
+ ".xlsx";
(new ExportExcel("订单数据", ShopPay.class)).setDataList(list)
.write(response, fileName).dispose();
return null;
} catch (Exception arg16) {
this.addMessage(redirectAttributes, new String[]{"导出用户失败!失败信息:"
+ arg16.getMessage()});
return "redirect:" + this.adminPath + "/pay/shopPay/list?repage";
}


}



优化后的JSP页面

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<title>订单信息管理</title>
<meta name="decorator" content="default"/>
<script type="text/javascript">



$(document).ready(function() {
$("#btnSubmitExcel").click(function(){
top.$.jBox.confirm("确认要导出用户数据吗?","系统提示",function(v,h,f){
if(v=="ok"){
$("#searchForm").attr("action","${ctx}/pay/shopPay/exportData");
$("#searchForm").submit(); 
}
},{buttonsFocus:1});
top.$('.jbox-body .jbox-icon').css('top','55px');
});

});
function page(n,s){
if(n) $("#pageNo").val(n);
if(s) $("#pageSize").val(s);
$("#searchForm").attr("action","${ctx}/pay/shopPay/list");
$("#searchForm").submit();
    return false;
    }
function searchToday(type){
$("#reportType").val(type);
$("#searchForm").submit();
}

//重置查询条件
function formReset() {  
        $(':input','#searchForm')  
         .not(':button, :submit, :reset, :hidden')  
         .val('')  
         .removeAttr('checked')  
         .removeAttr('selected');                    
    }  


</script>
</head>
<body>
<ul class="nav nav-tabs">
<li class="active"><a href="${ctx}/pay/shopPay/">订单信息列表</a></li>
<shiro:hasPermission name="order:shopOrder:edit"><li><a href="${ctx}/pay/shopPay/form">订单信息添加</a></li></shiro:hasPermission>
</ul>
<form:form id="searchForm" modelAttribute="pay" action="${ctx}/pay/shopPay/list" method="post" class="breadcrumb form-search">
<input type="hidden" value="" id="reportType" name="reportType"/>
<input id="pageNo" name="pageNo" type="hidden" value="${page.pageNo}"/>
<input id="pageSize" name="pageSize" type="hidden" value="${page.pageSize}"/>
<ul class="ul-form">
<li><label>商户号:</label>
<form:input id="assCode" path="assCode" htmlEscape="false" class="input-medium"/>
</li>
<li>
<label>商户订单号:</label>
<form:input id="assPayOrderNo" path="assPayOrderNo" htmlEscape="false"  class="input-medium"/>
</li>

<li>
<label>平台订单号:</label>
<form:input id="sysPayOrderNo" path="sysPayOrderNo" htmlEscape="false"  class="input-medium"/>
</li>

<li><label>通道订单号:</label>
<form:input id="channelPayOrderNo" path="channelPayOrderNo" htmlEscape="false" class="input-medium"/>
</li>


<li><label>从:</label>
<input id="beginTime" name="beginTime" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate"
value="${pay.beginTime}"
οnclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});"/>


</li>
<li><label>到:</label>
<input id="endTime" name="endTime" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate"
value="${pay.endTime}"
οnclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});"/>
</li>


<li><label>付款状态:</label>
<form:select id="payStatus" path="payStatus" class="input-xlarge" style="width:150px;">
<form:option value="" label="全部付款状态"/>
<form:options items="${payStatusList}"  htmlEscape="false"/>
</form:select>
</li>
<li><label>支付类型:</label>
<form:select id="paymentType" path="paymentType" class="input-xlarge" style="width:160px;">
<form:option value="" label="全部支付类型"/>
<form:options items="${payTypes}"  htmlEscape="false"/>
</form:select>
</li>
<li><label>订单类型:</label>
<form:select id="payRiskResult" name="payRiskResult" path="payRiskResult" class="input-xlarge" style="width:160px;">
<form:option value="" label="全部支订单类型"/>
<form:options items="${orderTypes}"  htmlEscape="false"/>
</form:select>
</li>
<li><label>支付通道:</label>
<select name="channelId" id="channelId" class="input-xlarge">
<option value="">全部支付通道</option>
<c:forEach items="${channels}" var="item">
<option value="${item.id}" <c:if test="${item.id==pay.channelId}"> selected</c:if>> ${item.channelName}</option>
</c:forEach>
</select>
</li>


<li class="btns"><input id="btnSubmit" class="btn btn-primary" type="submit" value="查询" οnclick="return page();"/></li>
<li class="btns"><input id="todayBtn" class="btn btn-primary" type="button" value="今日" οnclick="searchToday(1)"/></li>
<li class="btns"> <input id="todayBtn" class="btn btn-primary" type="button" value="昨日" οnclick="searchToday(2)"/></li>
<li class="btns"> <input id="todayBtn" class="btn btn-primary" type="button" value="本周" οnclick="searchToday(3)"/></li>
<li class="btns"> <input id="todayBtn" class="btn btn-primary" type="button" value="上周" οnclick="searchToday(4)"/></li>
<li class="btns"><li class="btns"> <input id="todayBtn" class="btn btn-primary" type="button" value="本月" οnclick="searchToday(5)"/></li>
<li class="btns"><input id="todayBtn" class="btn btn-primary" type="button" value="上月" οnclick="searchToday(6)"/></li>

<li class="btns"><input id="btnSubmitExcel" class="btn btn-primary" type="button" value="导出订单查询Excel表单" /></li>
<li class="btns"><input id="btnReset" class="btn btn-primary" type="button" οnclick="formReset()" value="清空查询条件" /></li>

<li class="clearfix"></li>
</ul>
</form:form>
<sys:message content="${message}"/>
<table id="contentTable" class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th colspan="4">
<span style="color:green">
成功交易:
<fmt:formatNumber type="number" value="${orderReport.successPayMoneyTotal}" pattern="0.000" maxFractionDigits="3"/>¥,
${orderReport.successPayCount}笔,
手续费[<fmt:formatNumber type="number" value="${orderReport.successPayCostTotal}" pattern="0.000" maxFractionDigits="3"/>]¥
</span>

</th>
<th colspan="4">
<span style="color:red">
失败交易:
<fmt:formatNumber type="number" value="${orderReport.failedPayMoneyTotal}" pattern="0.000" maxFractionDigits="3"/>¥,
${orderReport.failedPayCountTotal}笔,
</span>
</th>


<th colspan="4">
<span style="color:green">
交易金额成功率:<fmt:formatNumber type="number" value="${orderReport.rateMoney}" pattern="0.000" maxFractionDigits="3"/>%
</span>
<span style="color:green">
订单笔数成功率:<fmt:formatNumber type="number" value="${orderReport.rateCount}" pattern="0.000" maxFractionDigits="3"/>%
</span>
</th>
</tr> 
<tr>
<th>平台订单号</th>
<th>商户订单号</th>
<th>支付通道</th>
<th>支付类型</th>
<th>商户信息</th>
<th>付款状态</th>
<th>创建时间</th>
<th>支付时间</th>
<th>支付金额</th>
<th>手续费率</th>
<th>手续费用</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${page.list}" var="pay">
<tr>
<td>
<a href="#">
${pay.sysPayOrderNo}
</a>
</td>
<td>
${pay.assPayOrderNo}
</td>
<td>
${pay.channelCode}[${pay.channelId}]
</td>
<td>
${fns:getDisplayLabel(payTypes,pay.paymentType)}
</td>
<td>
${pay.assCode}[${pay.assId}]
</td>
<td>
<c:choose>
            <c:when test="${pay.payStatus=='60006'}">
            <span style="color:green;">
${fns:getDisplayLabel(payStatusList,pay.payStatus)}
</span>
          </c:when>
            <c:when test="${pay.payStatus=='60001'}">
            <span style="color:red;">
${fns:getDisplayLabel(payStatusList,pay.payStatus)}
</span>
          </c:when>
            <c:otherwise>
            <span style="color:blue;">
${fns:getDisplayLabel(payStatusList,pay.payStatus)}
</span>
          </c:otherwise>
        </c:choose>
</td>
<td>
<fmt:formatDate value="${pay.createDate}" pattern="yyyy-MM-dd HH:mm:ss"/>
</td>
<td>
<fmt:formatDate value="${pay.payCompleteTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
</td>
<td>
<fmt:formatNumber type="number" value="${pay.assPayMoney}" pattern="0.000" maxFractionDigits="3"/>
</td>
<td>
${pay.payAssCostRate}%
</td>
<td>
${pay.payAssCostMoney}元
</td>
<td>
<a href="${ctx}/pay/shopPay/notify?id=${pay.id}" class="btn" οnclick="return confirmx('确认要重新通知该订单吗?', this.href)">补通知</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<div class="pagination">${page}</div>
</body>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值