1.添加jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
2.导出工具类
package vitily.com.util;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @ClassName: ExportExcelUtils
* @Description: 导出Excel工具类
* @author lhy
* @date 2018年9月12日
*/
public class ExportExcelUtils {
private static final Logger logger =LoggerFactory.getLogger(ExportExcelUtils.class);
/**
* 导出Excel
* @param excelName 要导出的excel名称
* @param list 要导出的数据集合
* @param fieldMap 中英文字段对应Map,即要导出的excel表头
* @param response 使用response可以导出到浏览器
* @return
*/
public <T> void export(String excelName,List<T> list,LinkedHashMap<String, String> fieldMap,HttpServletResponse response){
if (excelName==null || excelName=="") {
excelName = new SimpleDateFormat("yyyyMMddhhmmss").format(
new Date()).toString();
}
response.reset();
response.setContentType("application/vnd.ms-excel");
try {
response.setHeader("Content-disposition", "attachment; filename="
+new String(excelName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
} catch (UnsupportedEncodingException e1) {
logger.info(e1.getMessage());
}
try {
HSSFWorkbook wb=new HSSFWorkbook();
HSSFSheet sheet=wb.createSheet(excelName);
HSSFCellStyle style=wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
fillSheet(sheet,list,fieldMap,style);
OutputStream ouputStream = response.getOutputStream();
wb.write(ouputStream);
ouputStream.flush();
ouputStream.close();
} catch (Exception e) {
logger.info("导出Excel失败!");
logger.error(e.getMessage());
}
}
/**
* 根据字段名获取字段对象
*
* @param fieldName
* 字段名
* @param clazz
* 包含该字段的类
* @return 字段
*/
public static Field getFieldByName(String fieldName, Class<?> clazz) {
logger.info("根据字段名获取字段对象:getFieldByName()");
Field[] selfFields = clazz.getDeclaredFields();
for (Field field : selfFields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null && superClazz != Object.class) {
return getFieldByName(fieldName, superClazz);
}
return null;
}
/**
* 根据字段名获取字段值
*
* @param fieldName 字段名
* @param o 对象
* @return 字段值
* @throws Exception 异常
*
*/
public static Object getFieldValueByName(String fieldName, Object o)
throws Exception {
logger.info("根据字段名获取字段值:getFieldValueByName()");
Object value = null;
Field field = getFieldByName(fieldName, o.getClass());
if (field != null) {
field.setAccessible(true);
value = field.get(o);
} else {
throw new Exception(o.getClass().getSimpleName() + "类不存在字段名 "
+ fieldName);
}
return value;
}
/**
* 根据带路径或不带路径的属性名获取属性值,即接受简单属性名,
* 如userName等,又接受带路径的属性名,如student.department.name等
*
* @param fieldNameSequence 带路径的属性名或简单属性名
* @param o 对象
* @return 属性值
* @throws Exception 异常
*
*/
public static Object getFieldValueByNameSequence(String fieldNameSequence,
Object o) throws Exception {
logger.info("根据带路径或不带路径的属性名获取属性值,即接受简单属性名:getFieldValueByNameSequence()");
Object value = null;
String[] attributes = fieldNameSequence.split("\\.");
if (attributes.length == 1) {
value = getFieldValueByName(fieldNameSequence, o);
} else {
Object fieldObj = getFieldValueByName(attributes[0], o);
String subFieldNameSequence = fieldNameSequence
.substring(fieldNameSequence.indexOf(".") + 1);
value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
}
return value;
}
/**
* 向工作表中填充数据
*
* @param sheet
* excel的工作表名称
* @param list
* 数据源
* @param fieldMap
* 中英文字段对应关系的Map
* @param style
* 表格中的格式
* @throws Exception
* 异常
*
*/
public static <T> void fillSheet(HSSFSheet sheet, List<T> list,
LinkedHashMap<String, String> fieldMap,HSSFCellStyle style) throws Exception {
logger.info("向工作表中填充数据:fillSheet()");
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];
int count = 0;
for (Entry<String, String> entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}
HSSFRow row=sheet.createRow((int)0);
for (int i = 0; i < cnFields.length; i++) {
HSSFCell cell=row.createCell(i);
cell.setCellValue(cnFields[i]);
cell.setCellStyle(style);
sheet.autoSizeColumn(i);
}
for (int index = 0; index < list.size(); index++) {
row = sheet.createRow(index + 1);
T item = list.get(index);
for (int i = 0; i < enFields.length; i++) {
Object objValue = getFieldValueByNameSequence(enFields[i], item);
String fieldValue = objValue == null ? "" : objValue.toString();
row.createCell(i).setCellValue(fieldValue);
}
}
}
}
3.实体类
package vitily.com.tb_entity.finance;
import com.alibaba.fastjson.annotation.JSONField;
import vitily.base.tb_entity.BaseEntity;
import vitily.com.consts.FundsTypeDesc;
import vitily.com.util.CentToYuanSerializer;
import vitily.com.util.EnumHelperUtil;
/**
* 描述:账户流水表的实体类
* @version
* @author: lether
* @创建时间: 2018-03-24
*/
public class TbAccountFlow{
/**
* @Fields {todo}
*/
private static final long serialVersionUID = 1L;
/**
* 入账会员ID
*/
private Integer memberId;
/**
* 操作金额(单位:分)
*/
@JSONField(serializeUsing= CentToYuanSerializer.class)
private Long amount;
/**
* 可用结余(单位:分)
*/
@JSONField(serializeUsing= CentToYuanSerializer.class)
private Long availableBalance;
/**
* 冻结结余(单位:分)
*/
@JSONField(serializeUsing= CentToYuanSerializer.class)
private Long freezeBalance;
/**
* 资金备注
*/
private String memo;
/**
* 资金类型
*/
private Integer fundsType;
/**
* 账户平台
*/
private Integer platform;
/**
* 关联表ID
*/
private Integer relationId;
/**
* 操作描述
*/
private String remark;
/**
* 0:收入,1:支出,2预授权收入3预授权支出
*/
private Integer direction;
/**
* 入账会员ID
* [whh]@return member_id 入账会员ID
*/
public Integer getMemberId() {
return memberId;
}
/**
* 入账会员ID
* @param memberId 入账会员ID
*/
public void setMemberId(Integer memberId) {
this.memberId = memberId;
}
/**
* 操作金额(单位:分)
* [whh]@return amount 操作金额(单位:分)
*/
public Long getAmount() {
return amount;
}
/**
* 操作金额(单位:分)
* @param amount 操作金额(单位:分)
*/
public void setAmount(Long amount) {
this.amount = amount;
}
/**
* 可用结余(单位:分)
* [whh]@return available_balance 可用结余(单位:分)
*/
public Long getAvailableBalance() {
return availableBalance;
}
/**
* 可用结余(单位:分)
* @param availableBalance 可用结余(单位:分)
*/
public void setAvailableBalance(Long availableBalance) {
this.availableBalance = availableBalance;
}
/**
* 冻结结余(单位:分)
* [whh]@return freeze_balance 冻结结余(单位:分)
*/
public Long getFreezeBalance() {
return freezeBalance;
}
/**
* 冻结结余(单位:分)
* @param freezeBalance 冻结结余(单位:分)
*/
public void setFreezeBalance(Long freezeBalance) {
this.freezeBalance = freezeBalance;
}
/**
* 资金备注
* [whh]@return memo 资金备注
*/
public String getMemo() {
return memo;
}
/**
* 资金备注
* @param memo 资金备注
*/
public void setMemo(String memo) {
this.memo = memo;
}
/**
* 资金类型
* [whh]@return funds_type 资金类型
*/
public Integer getFundsType() {
return fundsType;
}
/**
* 资金类型
* @param fundsType 资金类型
*/
public void setFundsType(Integer fundsType) {
this.fundsType = fundsType;
}
/**
* 账户平台
* [whh]@return platform 账户平台
*/
public Integer getPlatform() {
return platform;
}
/**
* 账户平台
* @param platform 账户平台
*/
public void setPlatform(Integer platform) {
this.platform = platform;
}
/**
* 关联表ID
* [whh]@return relation_id 关联表ID
*/
public Integer getRelationId() {
return relationId;
}
/**
* 关联表ID
* @param relationId 关联表ID
*/
public void setRelationId(Integer relationId) {
this.relationId = relationId;
}
/**
* 操作描述
* [whh]@return remark 操作描述
*/
public String getRemark() {
return remark;
}
/**
* 操作描述
* @param remark 操作描述
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* 0:收入,1:支出,2预授权收入3预授权支出
* [whh]@return direction 0:收入,1:支出,2预授权收入3预授权支出
*/
public Integer getDirection() {
return direction;
}
/**
* 0:收入,1:支出,2预授权收入3预授权支出
* @param direction 0:收入,1:支出,2预授权收入3预授权支出
*/
public void setDirection(Integer direction) {
this.direction = direction;
}
}
4.控制层
/**
* @Title: export
* @Description: 导出记录
* @return void
* @throws
*/
@RequestMapping(value = "/export", method = RequestMethod.POST)
public void export(HttpServletRequest request, HttpServletResponse response, TbAccountFlow queryEntity) throws Exception {
String excelName="账户流水表";
LinkedHashMap<String, String> fieldMap =new LinkedHashMap<String, String>() ;
fieldMap.put("memName", "用户名");
fieldMap.put("memRealName", "姓名");
fieldMap.put("fundsTypeDesc", "类型");
fieldMap.put("amount", "操作金额");
fieldMap.put("directionDesc", "收支");
fieldMap.put("availableBalance", "可用结余");
fieldMap.put("freezeBalance", "冻结结余");
fieldMap.put("platformDesc", "资金平台");
fieldMap.put("remark", "资金备注");
fieldMap.put("createDate", "创建时间");
List<TbAccountFlow> list = baseMapper.getListByBean(queryEntity);
JSON.toJSONString(list);
new ExportExcelUtils().export(excelName, list, fieldMap, response);
}