使用poi实现Excel的数据分页导出
第一步,所需jar包
pom.xml引入poi的maven依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
第二步,创建所需工具类
创建自定义注解类,控制需要导出的标题和字段
import java.lang.annotation.*;
@Documented
@Target({ElementType.METHOD, ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Excel {
/**
*
* @Title: head
* @Description: excel导出数据表表头
* @Author ouyangli
* @Date 2019年4月7日 15:10:56
* @Version 1.0.1
* @return
*/
String head() default "";
/**
*
* @Title: isDefault
* @Description: 是否为默认导出字段
* @Author ouyangli
* @Date 2019年4月7日 15:11:03
* @Version 1.0.1
* @return
*/
boolean isDefault() default false;
}
创建核心工具类
import com.easyfly.main.base.exception.BusinessException;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
/**
*
* @Title: ExcelExportUtils.java
* @Description: 导出Excel数据文档
* @Author ouyangli
* @Date 2019年4月7日 15:05:57
* @Version 1.0.1
*/
public class ExcelExportUtil<T> {
private static Logger log = LoggerFactory.getLogger(ExcelExportUtil.class);
private HSSFWorkbook workbook;// 工作薄
private HSSFSheet sheet;// 表格
private HSSFCellStyle headStyle;// 表头单元格样式
private HSSFCellStyle rowStyle;// 数据单元格样式
/**
*
* Title: initPageExcelExport Description: 初始化分页导出excel对象信息
*
* @Author ouyangli
* @Date 2019年4月7日 15:06:24
* @Version 1.0.1
* @param sheetName
*/
public void initPageExcelExport(String sheetName) {
log.debug("开始初始化分页导出Excel数据文档, sheetName :{}", sheetName);
// 声明一个工作薄
workbook = new HSSFWorkbook();
// 生成一个表格
sheet = workbook.createSheet(sheetName);
try {
// 设置表格默认列宽度为20个字节
sheet.setDefaultColumnWidth((short) 14);
// 设置表头单元格样式
headStyle = workbook.createCellStyle();
headStyle.setFillForegroundColor((short) 40);// HSSFColor.SKY_BLUE.index
headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headStyle.setAlignment(HorizontalAlignment.LEFT);
// 设置表头的字体样式
HSSFFont headFont = workbook.createFont();
headFont.setColor((short) 8);// HSSFColor.BLACK.index
headFont.setFontHeightInPoints((short) 12);
headFont.setBold(true);
headStyle.setFont(headFont);
// 设置数据单元格样式
rowStyle = workbook.createCellStyle();
rowStyle.setAlignment(HorizontalAlignment.LEFT);
rowStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置数据单元格字体样式
HSSFFont rowFont = workbook.createFont();
rowFont.setBold(false);
rowStyle.setFont(rowFont);
} catch (Exception e) {
throw new BusinessException("401", "初始化分页导出Excel文档失败", e);
}
}
/**
*
* Title: buildPageDataToExcel Description: 构建一页数据到excel对象中
*
* @Author ouyangli
* @Date 2019年4月7日 15:08:28
* @Version 1.0.1
* @param dataSet
* @param pattern
* @throws BusinessException
*/
public void buildPageDataToExcel(List<T> dataSet,List<String> extraColumnList, int startIndex, String pattern) throws BusinessException {
if (dataSet == null || dataSet.isEmpty())
throw new BusinessException("406", "导出数据集合对象为空");
if(extraColumnList == null)
extraColumnList = new ArrayList<>(0);
if (sheet != null && headStyle != null && rowStyle != null)
buildPageExcel(dataSet, extraColumnList, startIndex, pattern);
}
/**
*
* Title: commintDataToExcel Description: 提交分页数据到excel输出流中
*
* @Author ouyangli
* @Date 2019年4月7日 15:08:33
* @Version 1.0.1
* @param out
* @throws BusinessException
* @throws IOException
*/
public void commintDataToExcel(OutputStream out) throws BusinessException, IOException {
try {
workbook.write(out);
} catch (IOException e) {
throw new BusinessException("507", "workbook.write exception : " + e.getMessage(), e);
} finally {
workbook.close();
}
}
/**
*
* Title: exportExcel Description: 一次性导出所有数据到excel文件(适用少量数据导出)
*
* @Author ouyangli
* @Date 2019年4月7日 15:08:42
* @Version 1.0.1
* @param sheetName
* sheet页名称
* @param dataSet
* 导出数据集对象
* @param out
* 文件输出流
* @param pattern
* 时间类型格式
* @throws Exception
*/
public static <T> void exportExcel(String sheetName, List<T> dataSet, List<String> extraColumnList, OutputStream out, String pattern)
throws BusinessException {
if (dataSet == null || dataSet.isEmpty())
throw new BusinessException("406", "导出数据集合对象为空");
if(extraColumnList == null)
extraColumnList = new ArrayList<String>(0);
log.debug("开始导出Excel数据文档, sheetName :{}", sheetName);
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(sheetName);
try {
// 设置表格默认列宽度为20个字节
sheet.setDefaultColumnWidth((short) 22);
// 设置表头单元格样式
HSSFCellStyle headStyle = workbook.createCellStyle();
headStyle.setFillForegroundColor((short) 42);// HSSFColor.LIGHT_GREEN
headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headStyle.setAlignment(HorizontalAlignment.LEFT);
// 设置表头的字体样式
HSSFFont headFont = workbook.createFont();
headFont.setColor((short) 8);// HSSFColor.BLACK.index
headFont.setFontHeightInPoints((short) 11);
headFont.setBold(true);
headStyle.setFont(headFont);
// 设置数据单元格样式
HSSFCellStyle rowStyle = workbook.createCellStyle();
rowStyle.setAlignment(HorizontalAlignment.LEFT);
rowStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置数据单元格字体样式
HSSFFont rowFont = workbook.createFont();
rowFont.setBold(false);
rowStyle.setFont(rowFont);
// 加载excel数据信息
buildExcelData(sheet, headStyle, rowStyle, dataSet,extraColumnList, pattern);
workbook.write(out);
} catch (Exception e) {
throw new BusinessException("401", "导出Excel文档失败", e);
} finally {
try {
workbook.close();
} catch (IOException e) {
log.error("workbook.close exception : " + e.getMessage(), e);
}
}
}
/**
* @Description: 导出Excel模板文件
* @author ouyangli
* @date 2019年4月7日 15:08:57
* @param sheetName 工作表名
* @param clazz 头部对象
* @param out 输出流
*/
public static <T> void exportExcelModel(String sheetName, T clazz, OutputStream out) {
log.debug("开始导出Excel模板文件, sheetName :{}", sheetName);
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(sheetName);
try {
// 设置表格默认列宽度为20个字节
sheet.setDefaultColumnWidth((short) 12);
// 设置表头单元格样式
HSSFCellStyle headStyle = workbook.createCellStyle();
headStyle.setFillForegroundColor((short) 42);// HSSFColor.LIGHT_GREEN
headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headStyle.setAlignment(HorizontalAlignment.CENTER);
// 设置表头的字体样式
HSSFFont headFont = workbook.createFont();
headFont.setColor((short) 8);// HSSFColor.BLACK.index
headFont.setFontHeightInPoints((short) 11);
headFont.setBold(true);
headStyle.setFont(headFont);
// 加载excel模板头部信息
buildExcelModelHead(sheet, headStyle, clazz);
workbook.write(out);
} catch (Exception e) {
log.error("exportExcelModel() error 导出Excel模板文件异常", e);
} finally {
try {
workbook.close();
} catch (IOException e) {
log.error("exportExcelModel() --> workbook.close exception : " + e.getMessage(), e);
}
}
}
private static <T> void buildExcelModelHead(HSSFSheet sheet, HSSFCellStyle headStyle, T clazz) {
// 设置表格标题行
HSSFRow row = sheet.createRow(0);
Field[] heads = clazz.getClass().getDeclaredFields();
List<String> headList = new ArrayList<>();
// 获取字段注解的表头
for (int i = 0; i < heads.length; i++) {
// 过滤掉没加注解的字段 + 排除在外的列
if (heads[i].getAnnotations().length == 0 )
continue;
Excel exAnno = (Excel) heads[i].getAnnotations()[0];
if(exAnno.isDefault())
headList.add(exAnno.head());
}
for (int i = 0; i < headList.size(); i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(headStyle);
HSSFRichTextString text = new HSSFRichTextString(headList.get(i));
cell.setCellValue(text);
}
log.debug("excel模板表头信息构建完成 , 数据列总数:{}", headList.size());
}
/**
*
* Title: buildExcelData Description: 构建sheet数据表格内容
*
* @Author ouyangli
* @Date 2019年4月7日 15:12:10
* @Version 1.0.1
* @param sheet
* @param headStyle
* @param rowStyle
* @param dataSet
* @param pattern
*/
private static <T> void buildExcelData(HSSFSheet sheet, HSSFCellStyle headStyle, HSSFCellStyle rowStyle,
List<T> dataSet,List<String> extraColumnList, String pattern) {
// 设置表格标题行
HSSFRow row = sheet.createRow(0);
buildSheetTableHead(dataSet, extraColumnList, headStyle, row);
// 遍历集合数据,设置数据行
Iterator<T> it = dataSet.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T tObj = (T) it.next();
Field[] fields = tObj.getClass().getDeclaredFields();
List<Field> fieldsList = new ArrayList<Field>();
for (Field field : fields) {
if (field.getAnnotations().length == 0 )
continue;
Excel exAnno = (Excel) field.getAnnotations()[0];
if(exAnno.isDefault() || (!exAnno.isDefault() && extraColumnList.contains(field.getName())) )
fieldsList.add(field);
}
buildRowData(fieldsList, rowStyle, row, tObj, pattern);
}
}
private static <T> void buildRowData(List<Field> fieldsList, HSSFCellStyle rowStyle,HSSFRow row,T tObj, String pattern) {
Class<? extends Object> tCls = tObj.getClass();
for (Field field : fieldsList) {
HSSFCell cell = row.createCell(fieldsList.indexOf(field));
cell.setCellStyle(rowStyle);
String fieldName = field.getName();
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Object value = null;
try {
Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
value = getMethod.invoke(tObj, new Object[] {});
buildSheetDataTypeFormat(cell, value, pattern);
} catch (Exception e) {
log.error(" invoke method exception : " + e.getMessage(), e);
throw new BusinessException("501", " invoke method get value exception : " + e.getMessage(),e);
}
}
}
/**
*
* Title: buildPageExcel Description: 构建分页导出excel的列表数据
*
* @Author ouyangli
* @Date 2019年4月7日 15:12:18
* @Version 1.0.1
* @param dataSet
* @param startIndex
* @param pattern
*/
private void buildPageExcel(List<T> dataSet,List<String> extraColumnList, int startIndex, String pattern) {
if (startIndex == 0) {
// 设置表格标题行
HSSFRow row = sheet.createRow(0);
buildSheetTableHead(dataSet, extraColumnList, headStyle, row);
}
// 遍历集合数据,设置数据行
Iterator<T> it = dataSet.iterator();
HSSFRow row = null;
int index = startIndex;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T tObj = (T) it.next();
Field[] fields = tObj.getClass().getDeclaredFields();
List<Field> fieldsList = new ArrayList<>();
for (Field field : fields) {
// 过滤掉没加注解的字段 + 排除在外的列
if (field.getAnnotations().length == 0 )
continue;
Excel exAnno = (Excel) field.getAnnotations()[0];
if(exAnno.isDefault() || (!exAnno.isDefault() && extraColumnList.contains(field.getName())) )
fieldsList.add(field);
}
buildRowData(fieldsList, row, tObj, pattern);
}
}
private void buildRowData(List<Field> fieldsList,HSSFRow row,T tObj, String pattern) {
for (Field field : fieldsList) {
HSSFCell cell = row.createCell(fieldsList.indexOf(field));
cell.setCellStyle(rowStyle);
String fieldName = field.getName();
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Class<? extends Object> tCls = tObj.getClass();
Object value = null;
try {
Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
value = getMethod.invoke(tObj, new Object[] {});
buildSheetDataTypeFormat(cell, value, pattern);
} catch (Exception e) {
log.error(" invoke method exception : " + e.getMessage(), e);
throw new BusinessException("501", " invoke method get value exception : " + e.getMessage(),
e);
}
}
}
/**
*
* Title: buildSheetTableHead Description: 构建sheet表格的表头属性
*
* @Author ouyangli
* @Date 2019年4月7日 15:12:27
* @Version 1.0.1
* @param dataSet
* @param headStyle
* @param row
*/
private static <T> void buildSheetTableHead(List<T> dataSet, List<String> extraColumnList, HSSFCellStyle headStyle,
HSSFRow row) {
T tempT = dataSet.get(0);
Field[] heads = tempT.getClass().getDeclaredFields();
List<String> headList = new ArrayList<>();
// 获取字段注解的表头
for (int i = 0; i < heads.length; i++) {
// 过滤掉没加注解的字段 + 排除在外的列
if (heads[i].getAnnotations().length == 0 )
continue;
Excel exAnno = (Excel) heads[i].getAnnotations()[0];
if(exAnno.isDefault() || (!exAnno.isDefault() && extraColumnList.contains(heads[i].getName())) )
headList.add(exAnno.head());
}
for (int i = 0; i < headList.size(); i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(headStyle);
HSSFRichTextString text = new HSSFRichTextString(headList.get(i));
cell.setCellValue(text);
}
log.debug("excel数据表格表头信息构建完成 , 数据列总数:{}", headList.size());
}
/**
*
* Title: sheetDataTypeFormat Description: 判断值的类型后进行强制类型转换
*
* @Author ouyangli
* @Date 2019年4月7日 15:12:37
* @Version 1.0.1
* @param cell
* @param value
* @param pattern
*/
private static void buildSheetDataTypeFormat(HSSFCell cell, Object value, String pattern) {
String dataType = null;
if (value instanceof Integer) {
dataType = "Integer";
int intValue = (Integer) value;
cell.setCellValue(intValue);
} else if (value instanceof Float) {
dataType = "Float";
float fValue = (Float) value;
cell.setCellValue(fValue);
} else if (value instanceof Double) {
dataType = "Double";
double dValue = (Double) value;
cell.setCellValue(dValue);
} else if (value instanceof Long) {
dataType = "Long";
long longValue = (Long) value;
cell.setCellValue(longValue);
} else if (value instanceof Date) {
dataType = "Date";
Date date = (Date) value;
if (pattern == null || "".equals(pattern))
pattern = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
cell.setCellValue(sdf.format(date));
} else {
// 其它数据类型都当作字符串简单处理
String textValue = value == null ? "" : value.toString();
cell.setCellValue(textValue);
}
log.debug("excel数据表数据类型格式化完成: dataType:[{}], value:[{}]", dataType, value);
}
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
创建抛出异常类
若不用此类则将核心工具类的抛出异常改为Exception或其他异常类
public class BusinessException extends RuntimeException{
private static final long serialVersionUID = 4974085785488984511L;
private final String errorCode;
public BusinessException(String errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public BusinessException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public String getErrorCode() {
return this.errorCode;
}
}
第三步,测试(测试开始创建的实体类都可删除,仅供参考一个完整的调用过程,可根据自身项目修改)
创建所需导出数据的实体类
import com.easyfly.main.util.excel.Excel;
public class PbsRecordReportFormsVo {
@Excel(head = "勘验单位", isDefault = true)
private String kyUnitName;
private String kyUnitId;
@Excel(head = "未提交", isDefault = true)
private Integer notCommitNum;
@Excel(head = "已经提交", isDefault = true)
private Integer commitNum;
@Excel(head = "同步现堪", isDefault = true)
private Integer syncNum;
@Excel(head = "总数", isDefault = true)
private Integer total;
public String getKyUnitName() {
return kyUnitName;
}
public void setKyUnitName(String kyUnitName) {
this.kyUnitName = kyUnitName;
}
public String getKyUnitId() {
return kyUnitId;
}
public void setKyUnitId(String kyUnitId) {
this.kyUnitId = kyUnitId;
}
public Integer getNotCommitNum() {
return notCommitNum;
}
public void setNotCommitNum(Integer notCommitNum) {
this.notCommitNum = notCommitNum;
}
public Integer getCommitNum() {
return commitNum;
}
public void setCommitNum(Integer commitNum) {
this.commitNum = commitNum;
}
public Integer getSyncNum() {
return syncNum;
}
public void setSyncNum(Integer syncNum) {
this.syncNum = syncNum;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
创建查询参数类1
public class PbsRecordReportFormsRequest extends BasePageQuery {
private String kyUnitName; //勘验单位名称
private Date kyDateBegin; //勘验时间区间-->开始
private Date kyDateEnd; //勘验时间区间-->结束
private Boolean isFlag; //是否启用单位分类统计
private String kyrId; //勘验人编码
public String getKyUnitName() {
return kyUnitName;
}
public void setKyUnitName(String kyUnitName) {
this.kyUnitName = kyUnitName;
}
public Date getKyDateBegin() {
return kyDateBegin;
}
public void setKyDateBegin(Date kyDateBegin) {
this.kyDateBegin = kyDateBegin;
}
public Date getKyDateEnd() {
return kyDateEnd;
}
public void setKyDateEnd(Date kyDateEnd) {
this.kyDateEnd = kyDateEnd;
}
public Boolean getIsFlag() {
return isFlag;
}
public void setIsFlag(Boolean flag) {
isFlag = flag;
}
public String getKyrId() {
return kyrId;
}
public void setKyrId(String kyrId) {
this.kyrId = kyrId;
}
}
创建查询参数类2
public class BasePageQuery {
protected Integer currentPage = 1; // 当前页
protected Integer pageSize =20; // 每页显示记录数
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
}
创建响应工具类1
public enum CommonsEnum {
/**
* 当前页
*/
RESPONSE_PAGE_NUM("1", "当前页"),
/**
* 当前页显示记录数
*/
RESPONSE_PAGE_SIZE("10", "当前页显示记录数"),
/**
* 请求成功
*/
RESPONSE_200("200", "请求成功"),
/**
* 服务器错误
*/
RESPONSE_500("500", "服务器错误"),
RESPONSE_5501("5501", "数据查询失败"),
RESPONSE_5502("5502", "数据更新失败"),
RESPONSE_5503("5503", "数据删除失败"),
RESPONSE_5504("5504", "数据保存失败"),
RESPONSE_5505("5505", "业务处理异常"),
/**
* 接口错误
*/
RESPONSE_5001("5001", "服务器异常"),
/**
* 请求参数有误
*/
RESPONSE_400("400", "请求参数有误"),
/**
* 用户未登录
*/
RESPONSE_401("401", "用户未登录"),
/**
* 业务逻辑错误响应码
*/
RESPONSE_402("402", "业务逻辑错误响应码"),
/**
* 用户未授权
*/
RESPONSE_403("403", "用户未授权"),
/**
* 用户未授权
*/
RESPONSE_406("406", "用户登录已过期"),
/**
* 用户已存在
*/
RESPONSE_10000("10000", "用户已存在"),
/**
* 序号重复
*/
RESPONSE_10001("10001", "序号重复"),
/**
* 网关超时
*/
RESPONSE_504("504", "网关超时"),
/**
* 新增失败
*/
RESPONSE_600("600", "新增失败"),
/**
* 修改失败
*/
RESPONSE_601("601", "修改失败"),
/**
* 删除失败
*/
RESPONSE_602("602", "删除失败"),
/**
* id生成失败
*/
RESPONSE_700("700", "id生成失败"),
/**
* (第三方接口)短信发送异常
*/
RESPONSE_800("800", "短信发送异常"),
RESPONSE_801("801", "请求第三方接口异常"),
/**************************
* 定义文件上传响应码--start
***********************************/
/**
* 上传失败,上传图片数据为空
*/
RESPONSE_10003("10003", "上传失败,上传图片数据为空"),
/**
* 上传失败,数据不合法
*/
RESPONSE_10004("10004", "上传失败,数据不合法"),
/**
* 上传图片格式不合法
*/
RESPONSE_10005("10005", "上传图片格式不合法"),
/**
* 文件不存在
*/
RESPONSE_10100("10100", "文件不存在"),
/**
* 上传了一个空文件,请添加数据
*/
RESPONSE_10101("10101", "上传了一个空文件,请添加数据"),
/**
* 压缩包格式有误
*/
RESPONSE_10102("10102", "压缩包格式有误"),
/**
* Excel文件格式有误
*/
RESPONSE_10103("10103", "Excel文件格式有误"),
/**
* Excel文件解析错误
*/
RESPONSE_10104("10104", "Excel文件解析错误"),
RESPONSE_10105("10105", "推送文件至Xh服务器失败"),
RESPONSE_10106("10106", "服务器异常,上传文件失败"),
RESPONSE_10107("10107", "服务器异常,doc文档生成失败"),
/**************************
* 定义文件上传响应码--end
***********************************/
/**
* 查询结果不存在或返回空(空指针异常处理)
*/
RESPONSE_10006("10006", "记录不存在"),
;
CommonsEnum(String code, String name) {
this.code = code;
this.name = name;
}
private String code;
private String name;
public String getCode() {
return code;
}
public String getName() {
return name;
}
public static String getTextByKey(String pKey){
CommonsEnum[] payEnums = CommonsEnum.values();
for (CommonsEnum enumObj: payEnums) {
if(enumObj.getCode().equals(pKey)){
return enumObj.getName();
}
}
return pKey;
}
}
创建响应工具类2
import java.io.Serializable;
import java.util.List;
/**
* @Description 分页查询响应数据对象
* @Author ouyangli
* @Param
* @Return
* @Date 2019/4/4 0004 17:45
*/
public class QueryListResultVo<T> implements Serializable{
private static final long serialVersionUID = 7725607827335619043L;
private int pageNum; //当前页
private int pageSize; //页面容量
private int totalPage; //总页数
private long totalSize; //总记录数
private List<T> records; //数据集
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public long getTotalSize() {
return totalSize;
}
public void setTotalSize(long totalSize) {
this.totalSize = totalSize;
}
public List<T> getRecords() {
return records;
}
public void setRecords(List<T> records) {
this.records = records;
}
}
创建响应工具类3
import java.io.Serializable;
/**
* @Description 定义后台响应最终格式
* @Author ouyangli
* @Param
* @Return
* @Date 2019/4/4 0004 17:45
*/
public class Response<T> implements Serializable {
private static final long serialVersionUID = 4435099346743782566L;
private boolean isSuccess = true;// 响应状态 true/false
private String message = CommonsEnum.RESPONSE_200.getName(); //响应携带消息
private String code = CommonsEnum.RESPONSE_200.getCode(); //响应状态码
private T resultObject; //响应数据
public Response() {
}
public Response(T resultObject) {
this.resultObject = resultObject;
}
public Response(boolean isSuccess, T resultObject) {
this.isSuccess = isSuccess;
this.resultObject = resultObject;
}
public Response(boolean isSuccess, String message, String code) {
this.isSuccess = isSuccess;
this.message = message;
this.code = code;
}
public Response(boolean isSuccess, String message, String code, T resultObject) {
this.isSuccess = isSuccess;
this.message = message;
this.code = code;
this.resultObject = resultObject;
}
public boolean isSuccess() {
return this.isSuccess;
}
public void setSuccess(boolean success) {
this.isSuccess = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public T getResultObject() {
return this.resultObject;
}
public void setResultObject(T resultObject) {
this.resultObject = resultObject;
}
/**
* @Description 新增失败默认响应
* @Author ouyangli
* @Param
* @Return
* @Date 2019/4/4 0004 17:09
*/
public static Response returnSaveFailedResponse(Response resultResponse) {
resultResponse.setSuccess(false);
resultResponse.setCode(CommonsEnum.RESPONSE_5504.getCode());
resultResponse.setMessage(CommonsEnum.RESPONSE_5504.getName());
return resultResponse;
}
/**
* @Description 删除失败默认响应
* @Author
* @Param
* @Return
* @Date 2019/4/4 0004 17:08
*/
public static Response returnDelFailedResponse(Response resultResponse) {
resultResponse.setSuccess(false);
resultResponse.setCode(CommonsEnum.RESPONSE_5503.getCode());
resultResponse.setMessage(CommonsEnum.RESPONSE_5503.getName());
return resultResponse;
}
/**
* @Description 修改失败默认响应
* @Author ouyangli
* @Param
* @Return
* @Date 2019/4/4 0004 17:09
*/
public static Response returnUpdateFailedResponse(Response resultResponse) {
resultResponse.setSuccess(false);
resultResponse.setCode(CommonsEnum.RESPONSE_5502.getCode());
resultResponse.setMessage(CommonsEnum.RESPONSE_5502.getName());
return resultResponse;
}
/**
* @Description 查询失败默认响应
* @Author ouyangli
* @Param
* @Return
* @Date 2019/4/4 0004 17:10
*/
public static Response returnQueryFailedResponse(Response resultResponse) {
resultResponse.setSuccess(false);
resultResponse.setCode(CommonsEnum.RESPONSE_5501.getCode());
resultResponse.setMessage(CommonsEnum.RESPONSE_5501.getName());
return resultResponse;
}
/**
* @Description 查询无记录
* @Author ouyangli
* @Param
* @Return
* @Date 2019/4/4 0004 17:10
*/
public static Response returnNotFoundDataResponse(Response resultResponse) {
resultResponse.setSuccess(false);
resultResponse.setCode(CommonsEnum.RESPONSE_10006.getCode());
resultResponse.setMessage(CommonsEnum.RESPONSE_10006.getName());
return resultResponse;
}
/**
* @Description 参数异常
* @Author ouyangli
* @Param
* @Return
* @Date 2019/4/4 0004 17:10
*/
public static Response returnParamIsNullResponse(Response resultResponse) {
resultResponse.setSuccess(false);
resultResponse.setCode(CommonsEnum.RESPONSE_400.getCode());
resultResponse.setMessage(CommonsEnum.RESPONSE_400.getName());
return resultResponse;
}
/**
* @Description 服务器异常
* @Author ouyangli
* @Param
* @Return
* @Date 2019/4/4 0004 17:10
*/
public static Response returnExceptionResponse(Response resultResponse) {
resultResponse.setSuccess(false);
resultResponse.setCode(CommonsEnum.RESPONSE_500.getCode());
resultResponse.setMessage(CommonsEnum.RESPONSE_500.getName());
return resultResponse;
}
/**
* @Description 服务器异常
* @Author ouyangli
* @Param
* @Return
* @Date 2019/4/4 0004 17:10
*/
public static Response returnExceptionResponse(Response resultResponse,String errorMessage) {
resultResponse.setSuccess(false);
resultResponse.setCode(CommonsEnum.RESPONSE_500.getCode());
resultResponse.setMessage(errorMessage);
return resultResponse;
}
}
测试接口
@RestController
@RequestMapping("/reportForms")
public class ReportFormsController{
private static Logger log = LoggerFactory.getLogger(ReportFormsController.class);
@Autowired
private ReportFormsMapper reportFormsMapper;
/**
* @Description 提供的导出接口(http://ip:port/reportForms/export)
* @Author ouyangli
* @Date 2019年4月7日 15:17:42
* @Param
* @Return boolean
**/
@GetMapping(value = "/export")
public void exportUserList(PbsRecordReportFormsRequest params, HttpServletResponse response) throws Exception {
String fileName = URLEncoder.encode("勘验报表","UTF-8");
response.setContentType("application/binary;charset=UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
params.setPageSize(500);//分页导出每页500条记录
Response<QueryListResultVo<PbsRecordReportFormsVo>> resultResposne=this.queryPbsRecordReportForms(params);
if(resultResposne.isSuccess()) {
try (ServletOutputStream out = response.getOutputStream()){
ExcelExportUtil<PbsRecordReportFormsVo> excel = new ExcelExportUtil<>();
excel.initPageExcelExport("勘验报表");
long startDateTime = System.currentTimeMillis()/1000;
buildExcelData(excel, resultResposne.getResultObject(), params,startDateTime);
excel.commintDataToExcel(out);
} catch (IOException e) {
log.error("下载失败IOException",e);
}
}
}
/**
* @Description 分页构建Excel导出数据内容
* @Author ouyangli
* @Date 2019年4月7日 15:17:42
* @Param [export, resultList, pActivityParam]
* @Return boolean
**/
private boolean buildExcelData(ExcelExportUtil<PbsRecordReportFormsVo> export,QueryListResultVo<PbsRecordReportFormsVo> resultList, PbsRecordReportFormsRequest params,long startDateTime){
int pageTotalSize = resultList.getTotalPage();//获取总页数
List<PbsRecordReportFormsVo> dataSet = resultList.getRecords();
if(dataSet != null) {
long currentDateTime = System.currentTimeMillis()/1000;
long timeConsuming = currentDateTime - startDateTime;//计算导出数据消耗时间多少秒
int currentPage = params.getCurrentPage();
int startIndex = (currentPage - 1) * params.getPageSize();
export.buildPageDataToExcel(dataSet, null, startIndex, null);
currentPage = currentPage + 1;
if(currentPage > pageTotalSize || timeConsuming > 60){//分页数据导完或者导出时间超过60s时终止
return true;
}
params.setCurrentPage(currentPage);
Response<QueryListResultVo<PbsRecordReportFormsVo>> resultResposne=this.queryPbsRecordReportForms(params);
//递归调用,
buildExcelData(export,resultResposne.getResultObject(),params,startDateTime);
}
return false;
}
/**
* @Description 数据库中查询数据,模拟调用dao接口
* @Author ouyangli
* @Date 2019年4月7日 15:17:42
* @Param
* @Return
**/
private Response<QueryListResultVo<PbsRecordReportFormsVo>> queryPbsRecordReportForms(PbsRecordReportFormsRequest params){
Response<QueryListResultVo<PbsRecordReportFormsVo>> response =new Response<>();
try{
//这里用到mybatis分页插件,不会用自行百度
PageHelper.startPage(params.getCurrentPage(),params.getPageSize());
List<PbsRecordReportFormsVo> list=reportFormsMapper.queryPbsRecordReportForms(params);
if(CollectionUtils.isEmpty(list)){
return Response.returnNotFoundDataResponse(response);
}
PageInfo<PbsRecordReportFormsVo> pageInfo =new PageInfo<>(list);
QueryListResultVo<PbsRecordReportFormsVo> queryListResultVo =new QueryListResultVo<>();
//本页结果集
queryListResultVo.setRecords(list);
//总记录数
queryListResultVo.setTotalSize(pageInfo.getTotal());
//当前页
queryListResultVo.setPageNum(pageInfo.getPageNum());
//页面容量
queryListResultVo.setPageSize(pageInfo.getPageSize());
//总页数
queryListResultVo.setTotalPage(pageInfo.getPages());
response.setResultObject(queryListResultVo);
return response;
}catch (Exception e){
log.error("-------------勘验报表查询异常-->error:",e);
return Response.returnExceptionResponse(response);
}
}
}
从测试开始创建的实体类都可以根据自身项目要求删除,仅供参考全部调用过程