• 【Spring】数据导出为Excel的接口报java.io.IOException: UT010029: Stream is closed错误


    数据导出为Excel的接口报java.io.IOException: UT010029: Stream is closed错误

    实习时导师让写一个平台信息导出为Excel的功能,写完之后发现文件正常导出,但控制台一直报Stream is closed错误。在网上找了大半天,都说是使用 OutputStream时关闭了流导致的,这也确实是可能导致报错的原因之一,但我并未手动关闭OutputStream,排查半天,问了旁边大佬才知道文件下载接口不能有返回值。。。。。。。。。。因为接口被调用后response会自动关闭ServletOutputStream,而return时会再次自动关闭OutputStream,就会导致 Stream is closed问题。

    以下为问题记录(读者可忽略)

    导出文件正常:

    image-20230915155529371

    报错信息:

    image-20230915155316789

    java.io.IOException: UT010029: Stream is closed
    	at io.undertow.servlet.spec.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:138)
    	at com.fasterxml.jackson.core.json.UTF8JsonGenerator._flushBuffer(UTF8JsonGenerator.java:2171)
    	at com.fasterxml.jackson.core.json.UTF8JsonGenerator.flush(UTF8JsonGenerator.java:1184)
    	at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:1009)
    	at org.springblade.core.tool.jackson.AbstractReadWriteJackson2HttpMessageConverter.writeInternal(AbstractReadWriteJackson2HttpMessageConverter.java:116)
    	at org.springblade.core.tool.jackson.MappingApiJackson2HttpMessageConverter.writeInternal(MappingApiJackson2HttpMessageConverter.java:73)
    	at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:104)
    	at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:290)
    	at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:183)
    	at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78)
    	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:135)
    	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
    	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:497)
    	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:584)
    	at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
    	at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
    	at org.springblade.core.log.filter.LogTraceFilter.doFilter(LogTraceFilter.java:39)
    	at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    	at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    	at org.springblade.core.boot.request.BladeRequestFilter.doFilter(BladeRequestFilter.java:58)
    	at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    	at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    	at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:114)
    	at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    	at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    	at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    	at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    	at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    	at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    	at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)
    	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    	at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    	at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    	at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    	at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    	at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    	at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    	at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
    	at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    	at io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
    	at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:117)
    	at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    	at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    	at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    	at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    	at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    	at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    	at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    	at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    	at io.undertow.servlet.handlers.SendErrorPageHandler.handleRequest(SendErrorPageHandler.java:52)
    	at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    	at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:275)
    	at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:79)
    	at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:134)
    	at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:131)
    	at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    	at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    	at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:255)
    	at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:79)
    	at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:100)
    	at io.undertow.server.Connectors.executeRootHandler(Connectors.java:387)
    	at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:852)
    	at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    	at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2019)
    	at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1558)
    	at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1423)
    	at org.xnio.XnioWorker$WorkerThreadFactory$1$1.run(XnioWorker.java:1282)
    	at java.lang.Thread.run(Thread.java:750)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83

    报错接口如下:

    	@GetMapping("/exportExcel")
    	@ApiOperationSupport(order = 10)
    	@ApiOperation(value = "导出数据为Excel表格", notes = "导出数据为Excel表格")
    	public R exportExcel(@ApiParam(value = "表单id", required = true) @RequestParam Long formId,
    							@ApiParam(value = "数据列表ids", required = true) @RequestParam String ids,
    							HttpServletResponse response) {
    
    		List<Map<String, Object>> data;
    		List<Long> longIds = Func.toLongList(ids);
    
    		//通过表单id,获取表单配置
    		FormEntity formEntity = formService.getById(formId);
    		if (null == formEntity) {
    			return R.fail("未查询到表单");
    //			throw new ServiceException("未查询到表单");
    		}
    
    		// 标题字段name
    		Set<String> title;
    		// 导出的字段列表
    		List<FormFieldDTO> formLabels;
    		try {
    			Long modelId = formEntity.getModelId();
    			ModelBase model = modelBaseService.getById(modelId);
    			String tableName = model.getName();
    			Integer type = model.getType();
    
    			// 获取当前表单的字段信息
    			List<FormFieldDTO> formFields = formService.getFormFieldsInfoByFormId(formId);
    			Set<String> fieldSet = formFields.stream()
    				.filter(item -> item.getModelFieldId() != null)
    				.map(FormFieldDTO::getName)
    				.collect(Collectors.toSet());
    
    
    			// 更换数据源
    			Long dataSourceId = model.getSourceId();
    			if (dataSourceId != null) {
    				DynamicDataSourceContextHolder.push(dataSourceId.toString());
    			}
    
    			// 获取当前表单的所有字段
    			List<Map<String, Object>> fieldsList = baseSqlService.getAllFields(tableName, type);
    			Set<String> allFields = fieldsList.get(0).keySet();
    			// 求公共字段
    			fieldSet.retainAll(allFields);
    			// 获取公共字段对应的name
    			formLabels = formFields.stream().filter(item -> fieldSet.contains(item.getName())).collect(Collectors.toList());
    			// 判断数据库表中是否存在status字段
    			if (allFields.contains("status")){
    				fieldSet.add("status");
    			}
    
    			// 提取字段名
    			// 通过IFNULL函数解决mybatis映射Map时忽略控制字段问题
    			title = fieldSet;
    			String fields = String.join(",", fieldSet);
    
    			data = baseSqlService.queryFieldsByIds(tableName, fields, longIds);
    
    		} catch (Exception e) {
    			return R.fail(e.toString());
    //			e.printStackTrace();
    //			return;
    		} finally {
    			// 将数据源切换回来
    			DynamicDataSourceContextHolder.clear();
    		}
    
    		// 结果数据匹配中文信息
    		List<Map<String, Object>> recordsWrapper = BaseListRecordsWrapper.build().wrapper(data, formEntity.getStyleJson());
    
    		// 获取表单列表中不存在的字段名
    		// **此处需要创建新的HashSet对象,否则removeAll会删除原信息值**
    		Set<String> recordFields = new HashSet<>(recordsWrapper.get(0).keySet());
    		recordFields.removeAll(title);
    		recordFields.forEach(item -> {
    			FormFieldDTO formFieldDTO = new FormFieldDTO();
    			formFieldDTO.setName(item);
    			if ("statusName".equals(item)) {
    				formFieldDTO.setLabel("状态");
    			} else if ("create_user_name".equals(item)){
    				formFieldDTO.setLabel("创建人");
    			} else {
    				formFieldDTO.setLabel(item);
    			}
    			formLabels.add(formFieldDTO);
    		});
    		// 剔除原有的status,仅导出statusName即可
    		if (recordFields.contains("statusName")){
    			recordsWrapper.forEach(item -> item.remove("status"));
    			title.remove("status");
    		}
    		if (recordFields.contains("create_user_name")){
    			recordsWrapper.forEach(item -> item.remove("create_user"));
    			title.remove("create_user");
    		}
    		// 将多出的字段添加至标题(如statusName)
    		title.addAll(recordFields);
    
    		Date date = new Date();
    		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    		try {
    			ExportUtil.writeExcel(response, recordsWrapper, dateFormat.format(date), "默认页", title, formLabels);
    		} catch (IOException e) {
    			log.error(e.toString());
    		}
    
    		return R.success("下载成功!");
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112

    修改后:

    	@GetMapping("/exportExcel")
    	@ApiOperationSupport(order = 10)
    	@ApiOperation(value = "导出数据为Excel表格", notes = "导出数据为Excel表格")
    	public void exportExcel(@ApiParam(value = "表单id", required = true) @RequestParam Long formId,
    							@ApiParam(value = "数据列表ids", required = true) @RequestParam String ids,
    							HttpServletResponse response) {
    
    		List<Map<String, Object>> data;
    		List<Long> longIds = Func.toLongList(ids);
    
    		//通过表单id,获取表单配置
    		FormEntity formEntity = formService.getById(formId);
    		if (null == formEntity) {
    			throw new ServiceException("未查询到表单");
    		}
    
    		// 标题字段name
    		Set<String> title;
    		// 导出的字段列表
    		List<FormFieldDTO> formLabels;
    		try {
    			Long modelId = formEntity.getModelId();
    			ModelBase model = modelBaseService.getById(modelId);
    			String tableName = model.getName();
    			Integer type = model.getType();
    
    			// 获取当前表单的字段信息
    			List<FormFieldDTO> formFields = formService.getFormFieldsInfoByFormId(formId);
    			Set<String> fieldSet = formFields.stream()
    				.filter(item -> item.getModelFieldId() != null)
    				.map(FormFieldDTO::getName)
    				.collect(Collectors.toSet());
    
    
    			// 更换数据源
    			Long dataSourceId = model.getSourceId();
    			if (dataSourceId != null) {
    				DynamicDataSourceContextHolder.push(dataSourceId.toString());
    			}
    
    			// 获取当前表单的所有字段
    			List<Map<String, Object>> fieldsList = baseSqlService.getAllFields(tableName, type);
    			Set<String> allFields = fieldsList.get(0).keySet();
    			// 求公共字段
    			fieldSet.retainAll(allFields);
    			// 获取公共字段对应的name
    			formLabels = formFields.stream().filter(item -> fieldSet.contains(item.getName())).collect(Collectors.toList());
    			// 判断数据库表中是否存在status字段
    			if (allFields.contains("status")){
    				fieldSet.add("status");
    			}
    
    			// 提取字段名
    			// 通过IFNULL函数解决mybatis映射Map时忽略控制字段问题
    			title = fieldSet;
    			String fields = String.join(",", fieldSet);
    
    			data = baseSqlService.queryFieldsByIds(tableName, fields, longIds);
    
    		} catch (Exception e) {
    			e.printStackTrace();
    			return;
    		} finally {
    			// 将数据源切换回来
    			DynamicDataSourceContextHolder.clear();
    		}
    
    		// 结果数据匹配中文信息
    		List<Map<String, Object>> recordsWrapper = BaseListRecordsWrapper.build().wrapper(data, formEntity.getStyleJson());
    
    		// 获取表单列表中不存在的字段名
    		// **此处需要创建新的HashSet对象,否则removeAll会删除原信息值**
    		Set<String> recordFields = new HashSet<>(recordsWrapper.get(0).keySet());
    		recordFields.removeAll(title);
    		recordFields.forEach(item -> {
    			FormFieldDTO formFieldDTO = new FormFieldDTO();
    			formFieldDTO.setName(item);
    			if ("statusName".equals(item)) {
    				formFieldDTO.setLabel("状态");
    			} else if ("create_user_name".equals(item)){
    				formFieldDTO.setLabel("创建人");
    			} else {
    				formFieldDTO.setLabel(item);
    			}
    			formLabels.add(formFieldDTO);
    		});
    		// 剔除原有的status,仅导出statusName即可
    		if (recordFields.contains("statusName")){
    			recordsWrapper.forEach(item -> item.remove("status"));
    			title.remove("status");
    		}
    		if (recordFields.contains("create_user_name")){
    			recordsWrapper.forEach(item -> item.remove("create_user"));
    			title.remove("create_user");
    		}
    		// 将多出的字段添加至标题(如statusName)
    		title.addAll(recordFields);
    
    		Date date = new Date();
    		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    		try {
    			ExportUtil.writeExcel(response, recordsWrapper, dateFormat.format(date), "默认页", title, formLabels);
    		} catch (IOException e) {
    			log.error(e.toString());
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106

    再次调用接口已无报错:

    image-20230915155607055

  • 相关阅读:
    阿里P8大佬,带来的Tomcat架构详解,真的颠覆你的认知
    数据库三范式
    MySQL--数据库基础
    线上业务优化之案例实战
    鸿蒙开发工具的汉化
    【Vue面试题二十七】、你了解axios的原理吗?有看过它的源码吗?
    【gitlab】我的gitlab经历--20220901
    提高Python并发性能 - asyncio/aiohttp介绍
    HANA SQL 的Union和Union All
    微信公众号授权登录后报redirect_uri参数错误的问题
  • 原文地址:https://blog.csdn.net/m0_47015897/article/details/132905846