java - 如何强制下载 Excel 文件?

标签 java grails apache-poi

我正在使用 Grails。 我有一个下载 Excel 文件的示例代码:

XSSFWorkbook workbook = new XSSFWorkbook()
....
FileOutputStream out = new FileOutputStream(new File("C:\\excel.xlsx"))
workbook.write(out)
out.close()

此处将自动下载 Excel 文件。我希望系统提示用户在浏览器窗口中下载文件。 我尝试使用以下代码:

response.setHeader("Cache-Control", "public")
response.setContentType("application/vnd.ms-excel")
response.setHeader('Content-Disposition', 'Attachment;Filename="excel.xlsx"')
ServletOutputStream outputStream = response.getOutputStream()
workbook.write(outputStream)
outputStream.flush()
outputStream.close()

这不起作用。如何实现这一目标?

提前致谢。

最佳答案

引用表格W3C

Parameter values are normally case sensitive, but certain parameters are interpreted to be case- insensitive, depending on the intended use. (For example, multipart boundaries are case-sensitive, but the "access- type" for message/External-body is not case-sensitive.)

所以,尝试改变

response.setHeader('Content-Disposition', 'Attachment;Filename="excel.xlsx"')

response.setHeader('Content-Disposition', 'attachment;filename="excel.xlsx"')

关于java - 如何强制下载 Excel 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34028838/

相关文章:

java - "Package should contain a content type part [M1.13]"

java - 是否可以使用 usermodel 编写 Excel 文件并使用 apache poi 中的 eventmodel 再次读取同一文件

java - 未找到 Android SDK 中的某些 .java 源代码

java - JUnit 测试用例获取数据库连接以及 play 框架、spring jdbctemplate 的问题?

grails - Grails 2.1在JBoss上禁用log4j配置

groovy - Grails 中测试/开发模式的自定义 init

java - POI 公式评估器 IFERROR

java - 在 wordpress post 中获取异常

java - 逻辑排序大写字母和数字的混合字符串

grails - 在GroovyShell中评估大型Groovy脚本