【问题标题】:Download Excel as xlsx instead of zip format in Scalatra在 Scalatra 中将 Excel 下载为 xlsx 而不是 zip 格式
【发布时间】:2017-07-25 14:56:27
【问题描述】:

我正在将使用 Apache POI 创建的 Excel 工作簿直接写入响应对象,如下所示,而不创建文件:

val outputStream: ByteArrayOutputStream = new ByteArrayOutputStream()
workbook.write(outputStream)
ExcelOk(response.getOutputStream.write(outputStream.toByteArray))

但是一旦响应的大小超过 8kB,它就会开始在 Chrome 中下载为 zip 文件,在 FireFox 中下载为 octet-stream。

我的ExcelOk 对象如下所示:

object ExcelOk {
  def apply(body: Any = Unit, headers: Map[String, String] = ExcelContentType, reason: String = "") = {
    halt(ActionResult(responseStatus(200, reason), body, headers ))
  }
}

我的ExcelContentType(即响应头)如下:

val ExcelContentType = Map(
  "Access-Control-Allow-Credentials" -> "true",
  "Access-Control-Allow-Methods" -> "GET, PUT, POST, DELETE, OPTIONS",
  "Access-Control-Allow-Origin" -> "*",
  "Access-Control-Max-Age" -> "1728000",
  "Content-type" -> "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  "Content-disposition" -> "attachment; filename=excel_report.xlsx"
)

我什至尝试将"Transfer-Encoding" -> "chunked" 添加到标题列表中,但它不起作用。

我也在我的web.xml 文件中添加了这个 sn-p,但它也没有帮助:

<mime-mapping>
  <extension>xlsx</extension>
  <mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type>
</mime-mapping>

任何有关这方面的帮助都会很有用。请注意,只有在响应大小超过某个阈值后才会观察到此行为。

【问题讨论】:

    标签: web.xml scalatra


    【解决方案1】:

    在将内容写入响应输出流之前,您必须设置响应标头。

    response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    response.setHeader("Content-disposition", "attachment; filename=excel_report.xlsx")
    
    workbook.write(response.getOutputStream)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 2014-07-22
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多