There is a data report as the following in my project, I want to export it as excel: But the wierd thing is that sometimes it exports successfully and sometimes failed. I have tried many times and it turns out that when the excel sheet is over 17 lines, it will lead to this:
It's sure that the excel is successfully created even if it exports failed, because I have written it to disk and checked the file. The following is the controller, what goes wrong with me?
@RequestMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response, ReportCondition condition){
try {
List<HashMap<String, String>> mapList = reportFormService.find(condition);
if(mapList == null || mapList.size() == 0){
logger.info("No reports...");
}
Map<String, Date> dateMap = DateConditionUtil.getStartEndDate1(condition.getStartDate(), condition.getEndDate());
String startDate = DateFormatUtils.format(dateMap.get("startDate"), "yyyyMMdd");
String endDate = DateFormatUtils.format(dateMap.get("endDate"), "yyyyMMdd");
String[] titleArr = new String[]{"序号","日期","应用系统","短信服务商","请求发送总数","请求成功数量","实际短信条数","实际成功条数","费用","失败数量","成功率"};
String[] fieldArr = new String[]{"ID","RECORDDATE","APPNAME","PROVIDERNAME","SENDCOUNT","SUCCESSCOUNT","SENDSUM","SUCCESSSUM","TOTALFEE","FAILURECOUNT","SUCCESSRATE"};
ByteArrayOutputStream os = new ByteArrayOutputStream();
WorkBookUtil.createExcel(titleArr, fieldArr, mapList, os);
try(BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(os.toByteArray()));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())){
byte[] buff = new byte[1024];
int bytes;
while (-1 != (bytes = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytes);
}
bos.flush();
}catch (Exception e){
logger.error(e);
}
response.setCharacterEncoding("utf-8");
response.setHeader("content-disposition", "attachment;filename=" + String.format("%s-%s.xls", startDate, endDate));
response.setContentType("application/vnd.ms-excel;charset=utf-8");
} catch (IOException e){
logger.error("Export failed", e);
}
}
Try adding your response headers before writing the bytes out to the user. It would help to add a content-length header as well. You can get that after your call to createExcel
with os.toByteArray().length
. In addition close()
your bos
after you flush()
it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments