本文主要是介绍【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
问题。
以下为问题记录(读者可忽略)
导出文件正常:
报错信息:
java.io.IOException: UT010029: Stream is closedat 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)
报错接口如下:
@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("未查询到表单");}// 标题字段nameSet<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);// 获取公共字段对应的nameformLabels = 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("下载成功!");}
}
修改后:
@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("未查询到表单");}// 标题字段nameSet<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);// 获取公共字段对应的nameformLabels = 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());}}
再次调用接口已无报错:
这篇关于【Spring】数据导出为Excel的接口报java.io.IOException: UT010029: Stream is closed错误的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!