直接上代码
/**
* 按批次下载结果
* @param response
* @param batchId
* @throws IOException
*/
@GetMapping("/coupon/result/export/{batchId}")
public void getBatchCouponResultExcel(HttpServletResponse response, @PathVariable Integer batchId) throws IOException {
couponOperationService.getBatchCouponResultExcel( response,batchId) ;
}
private static String[] header1 = {"手机号", "单张优惠券编号", "操作", "操作结果"};
private static String[] header2 = {"手机号", "单张优惠券编号", "操作", "新过期时间","操作结果"};
public void getBatchCouponResultExcel(HttpServletResponse response, Integer batchId) throws IOException {
CouponOperateBatch couponOperateBatch = couponOperateBatchMapper.selectByPrimaryKey( batchId );
List<CouponOperate> list = couponOperateMapper.selectByBatchId( batchId, null );
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("结果明细");
sheet.setDefaultColumnWidth(18);
HSSFCellStyle headerStyle = ExcelUtils.genHeaderStyle(workbook);
HSSFCellStyle dataStyle = ExcelUtils.genDataStyle(workbook);
if(CouponOperateTypeEnum.DELAY.toString().equals( couponOperateBatch.getOperateType() )){
ExcelUtils.setHeader(header2, sheet, headerStyle);
}else{
ExcelUtils.setHeader(header1, sheet, headerStyle);
}
List<List<String>> data = getOperatesData(list,couponOperateBatch.getOperateType());
int row = 1;
if (CollectionUtils.isNotEmpty(data)) {
for (List<String> rowData : data) {
HSSFRow dataRow = sheet.createRow(row);
for (int x = 0; x < rowData.size(); x++) {
HSSFCell cell = dataRow.createCell(x);
cell.setCellStyle(dataStyle);
HSSFRichTextString text = new HSSFRichTextString(rowData.get(x));
cell.setCellValue(text);
}
row++;
}
}
String fileName = MessageFormat.format(CouponOperateTypeEnum.valueOf(couponOperateBatch.getOperateType()).getName()+"批量结果明细表{0}-{1}", DateUtil.getNowDate(),batchId);
response.reset();
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
//刷新缓冲
response.flushBuffer();
workbook.write(response.getOutputStream());
}
private List<List<String>> getOperatesData(List<CouponOperate> list, String operateType) {
List<List<String>> result = Lists.newArrayList();
for (CouponOperate operate : list) {
List<String> data = Lists.newArrayList();
data.add(operate.getPhone() ==null? "": operate.getPhone() );
data.add( operate.getCouponCode() );
data.add( CouponOperateTypeEnum.valueOf(operate.getOperateType()).getName() );
if(CouponOperateTypeEnum.DELAY.toString().equals( operateType)){
data.add(DateUtil.getDateTime(operate.getDelayTime()) );
}
data.add( OperateResultEnum.valueOf(operate.getOperateResult() ).getName() );
result.add( data );
}
return result;
}
效果
ExcelUtils :https://blog.csdn.net/qq_36609053/article/details/110648554