下载excel功能需要用到HttpServletResponse,注入一直报错,java.lang.IllegalStateException: getOutputStream() has already been called for this response
@Resource HttpServletResponse httpServletResponse;
使用注入的方法没问题
刚开始用的gson报栈溢出的错误,后来换成了fastjson报这个错误,最后定位在日志aop这里,会将HttpServletResponse 当做传过来的参数解析 冲突报错,
方法一,注释日志改用手每条controller手动加log的方法;
方法二,使用@resource注入获得HttpServletResponse ;
另外附上刚找到可以使用的excel导出代码
@Slf4j public class ExcelUtil { /** * 导出excel * * @param fileName excel文件名称 * @param sheetName excel sheet名称 * @param list 数据 * @param clazz * @param response */ public static void exportExcel(String fileName, String sheetName, List<?> list, Class<?> clazz, HttpServletResponse response){ ServletOutputStream outputStream; try { response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf8"); fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx"); outputStream = response.getOutputStream(); EasyExcel.write(outputStream) .head(clazz) .excelType(ExcelTypeEnum.XLSX) .sheet(sheetName) .doWrite(list); outputStream.flush(); } catch (Exception e) { log.error("导出excel异常:{}",e.getMessage()); e.printStackTrace(); } } }
使用方法
public void downloadPerformanceTemplate(HttpServletResponse response) { List<UserDetailDO> userDetailDOS = userDetailMapper.selectList(new LambdaQueryWrapper<UserDetailDO>().orderByAsc(UserDetailDO::getDeptId)); List<TemporaryPerformanceVO> collect = userDetailDOS.stream().map(t -> { TemporaryPerformanceVO temporaryPerformanceVO = new TemporaryPerformanceVO(); BeanUtils.copyProperties(t, temporaryPerformanceVO); temporaryPerformanceVO.setUserName(t.getName()); temporaryPerformanceVO.setOvertime(0); temporaryPerformanceVO.setNightShift(0); temporaryPerformanceVO.setSickLeave(0); return temporaryPerformanceVO; }).collect(Collectors.toList()); ExcelUtil.exportExcel("绩效模板","绩效模板",collect,TemporaryPerformanceVO.class ,response); }
标签:excel,HttpServletResponse,param,fileName,参数,报错,response,temporaryPerformanceVO From: https://www.cnblogs.com/zhahewei/p/18071305