【Spring】数据导出为Excel的接口报java.io.IOException: UT010029: Stream is closed错误
作者:mmseoamin日期:2024-01-19

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

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

导出文件正常:

【Spring】数据导出为Excel的接口报java.io.IOException: UT010029: Stream is closed错误,image-20230915155529371,第1张

报错信息:

【Spring】数据导出为Excel的接口报java.io.IOException: UT010029: Stream is closed错误,image-20230915155316789,第2张

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.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.access0(ServletInitialHandler.java:79)
	at io.undertow.servlet.handlers.ServletInitialHandler.call(ServletInitialHandler.java:134)
	at io.undertow.servlet.handlers.ServletInitialHandler.call(ServletInitialHandler.java:131)
	at io.undertow.servlet.core.ServletRequestContextThreadSetupAction.call(ServletRequestContextThreadSetupAction.java:48)
	at io.undertow.servlet.core.ContextClassLoaderSetupAction.call(ContextClassLoaderSetupAction.java:43)
	at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:255)
	at io.undertow.servlet.handlers.ServletInitialHandler.access推广代运营公司0(ServletInitialHandler.java:79)
	at io.undertow.servlet.handlers.ServletInitialHandler.handleRequest(ServletInitialHandler.java:100)
	at io.undertow.server.Connectors.executeRootHandler(Connectors.java:387)
	at io.undertow.server.HttpServerExchange.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.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> data;
		List longIds = Func.toLongList(ids);
		//通过表单id,获取表单配置
		FormEntity formEntity = formService.getById(formId);
		if (null == formEntity) {
			return R.fail("未查询到表单");
//			throw new ServiceException("未查询到表单");
		}
		// 标题字段name
		Set title;
		// 导出的字段列表
		List formLabels;
		try {
			Long modelId = formEntity.getModelId();
			ModelBase model = modelBaseService.getById(modelId);
			String tableName = model.getName();
			Integer type = model.getType();
			// 获取当前表单的字段信息
			List formFields = formService.getFormFieldsInfoByFormId(formId);
			Set 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> fieldsList = baseSqlService.getAllFields(tableName, type);
			Set 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> recordsWrapper = BaseListRecordsWrapper.build().wrapper(data, formEntity.getStyleJson());
		// 获取表单列表中不存在的字段名
		// **此处需要创建新的HashSet对象,否则removeAll会删除原信息值**
		Set 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> data;
		List longIds = Func.toLongList(ids);
		//通过表单id,获取表单配置
		FormEntity formEntity = formService.getById(formId);
		if (null == formEntity) {
			throw new ServiceException("未查询到表单");
		}
		// 标题字段name
		Set title;
		// 导出的字段列表
		List formLabels;
		try {
			Long modelId = formEntity.getModelId();
			ModelBase model = modelBaseService.getById(modelId);
			String tableName = model.getName();
			Integer type = model.getType();
			// 获取当前表单的字段信息
			List formFields = formService.getFormFieldsInfoByFormId(formId);
			Set 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> fieldsList = baseSqlService.getAllFields(tableName, type);
			Set 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> recordsWrapper = BaseListRecordsWrapper.build().wrapper(data, formEntity.getStyleJson());
		// 获取表单列表中不存在的字段名
		// **此处需要创建新的HashSet对象,否则removeAll会删除原信息值**
		Set 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错误,image-20230915155607055,第3张