POI匯出Excel表格異常:cannot call getWriter() after getOutputStream()
阿新 • • 發佈:2019-01-09
開發環境的伺服器是Tomcat,測試環境的伺服器是WebLogic。開發匯出功能選用元件POI,同時想在使用者匯出資料時同時彈出匯出框,讓使用者自由選擇下載位置。在Tomcat環境下匯出資料時沒有問題, WebLogic環境下測試發現匯出資料拋異常。
異常資訊: java.lang.IllegalStateException: strict servlet API: cannot call getWriter() after getOutputStream()
異常程式碼寫法如下:
//匯出
String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss" ).format(new Date()) +".xls";
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
response.setCharacterEncoding("utf-8");
wb.write(response.getOutputStream());
追其原因,網上有說兩者不能同時使用,也有說是weblogic的問題
連線地址3
連線地址4
最終解決方案
/**
* 匯出Excel
*/
@RequestMapping("/exportExcel")
public String exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception{
//獲取查詢條件
Map<String, Object> paramMap = this.getRequestParamMap(request);
//定義表的標題
String[] header = {"序號" ,"ID","姓名","性別","年齡","地址"};
//定義表的內容
List<Object[]> contentsList = service.getExportData(paramMap);
//匯出Excel
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
Workbook wb = excelUtil.getWorkbook(header, contentsList);
wb.write(os);
} catch (Exception e) {
e.printStackTrace();
}
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
//設定response引數,可以開啟下載頁面
response.reset();
response.setContentType("application/vnd.ms-excel; charset=utf-8") ;
response.setHeader("Content-Disposition", "attachment; filename=" + excelUtil.getFileName());
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;
}