2017-07-25 47 views
0

我正在写使用Apache POI响应对象的情况下直接创建一个文件,如下所示Excel工作簿中创建ZIP格式:下载Excel作为XLSX代替了Scalatra

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文件添加了这个片段,以及,但它并没有帮助:

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

任何有关这帮助将是有益的。请注意,只有在响应大小超过特定阈值后才会观察到此行为。

回答

1

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

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

workbook.write(response.getOutputStream)