我有下面的代码。当我尝试将记录列表导出到具有少量记录(大约 200 条记录)的 excel 时,这很好用:
@Path("/toExcel")
@GET
public Response excelCustomersReport(@QueryParam("page") Integer page, @QueryParam("start") Integer start, @QueryParam("limit") Integer limit, @QueryParam("filter") FilterWrapper filter, @QueryParam("sort") SortWrapper sort) throws Exception {
response.setContentType("application/octet-stream");
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String currentDateTime = dateFormatter.format(new Date());
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=report_" + currentDateTime + ".xlsx";
response.setHeader(headerKey, headerValue);
HSSFWorkbook workbook=userService.export(page,start,limit,filter,sort);
ServletOutputStream outputStream=response.getOutputStream();
workbook.write(outputStream);
workbook.close();
outputStream.close();
return ResponseHelper.ok(response);
}
当列表变大(前 200 多条记录)时,悲剧就开始了。它给出了以下错误:
<An I/O error has occurred while writing a response message entity to the container output stream.
org.glassfish.jersey.server.internal.process.MappableException: java.io.IOException: CLOSED
我搜索了很多,最终得到了这个解决方案:
public Response excelCustomersReport(@QueryParam("page") Integer page, @QueryParam("start") Integer start, @QueryParam("limit") Integer limit, @QueryParam("filter") FilterWrapper filter, @QueryParam("sort") SortWrapper sort) throws Exception {
response.setContentType("application/octet-stream");
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String currentDateTime = dateFormatter.format(new Date());
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=report_" + currentDateTime + ".xlsx";
response.setHeader(headerKey, headerValue);
HSSFWorkbook workbook=userService.export(page,start,limit,filter,sort);
response.setHeader("Content-Length", String.valueOf(workbook.getBytes().length));
InputStream is=new ByteArrayInputStream(workbook.getBytes());
ServletOutputStream sos = response.getOutputStream();
long byteRead = 0;
try {
byte[] buf = new byte[1000];
while (true) {
int r = is.read(buf);
if (r == -1)
break;
sos.write(buf, 0, r);
byteRead +=r;
if(byteRead > 1024*1024){ //flushes after 1mb
byteRead = 0;
sos.flush();
}
}
}catch (Exception e) {
e.printStackTrace();
}finally{
if(sos != null){
sos.flush();
}
try{is.close();}catch(Exception e){}
try{sos.close();}catch(Exception e){}
}
return ResponseHelper.ok(response);
}
冲洗溪流是大多数人指向的唯一方式。现在这个解决方案不仅适用于大数据,也适用于较小的数据(不适用于两种情况)。它给出了这个错误:
An I/O error has occurred while writing a response message entity to the container output stream.
org.glassfish.jersey.server.internal.process.MappableException: com.fasterxml.jackson.databind.JsonMappingException: Direct self-reference leading to cycle
我试过XSSFWorkbook
而不是HSSFWorkbook
。但 weblogic 甚至没有构建项目并引发了与meta-model
.
无论如何,这段代码有什么问题。如何将较大的文件写入流?我的 apache poi 版本是 3.11。