首页 > 解决方案 > 第一次尝试导出excel时出错

问题描述

 def exportExcel(){
        if(!params.max) params.max = 10

        if(params?.type && params.type != "html"){

            response.contentType = grailsApplication.config.grails.mime.types[params.type]
            response.setHeader("Content-disposition", "attachment; filename=agents.${params.extension}")

            List fields = ["orgTypeId", "name"]
            Map labels = ["orgTypeId":"DP Id", "name":"Name"]

            def upperCase = { domain, value ->
                return value.toUpperCase()
            }

            Map parameters = [title: "Agent List", "column.widths":[0.15, 0.4]]
            Map formatters = [name: upperCase]

            exportService.export(params.type, response.outputStream, Agent.list(params), fields, labels, formatters, parameters)
        }

        render(view: 'index',model: [organizationTypeCount: Agent.count(), organizationType: Agent.list(params)])

    }

这是我导出excel的代码。当我点击导出按钮时。它显示失败的网络错误。如果我继续下载,它将被下载。

这是错误:java.lang.IllegalStateException: getOutputStream() has already been called for this response

在此处输入图像描述

在此处输入图像描述

请帮我解决这个问题。

标签: grailsexport

解决方案


您不能将附件数据写入输出流,然后渲染索引视图;这是试图将您的视图呈现到您已将附件发送到的相同输出流。如果您删除渲染索引视图的行,您的代码应该可以按预期工作。

如果您需要生成附件/下载并移动到浏览器中的另一个视图,则需要发送两个请求来执行此操作。


推荐阅读