下載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); }