java web开发中大量数据导出Excel超时(504)问题解决
importjava.io.IOException;
importjava.io.OutputStream;
importjava.lang.reflect.Field;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importjava.util.Map.Entry;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.commons.lang3.StringUtils;
importorg.joda.time.DateTime;
importcom.travelzen.framework.net.http.TZHttpClient;
importcom.travelzen.tops.front.ota.member.item.CustomerItem;
publicclassCSV{
/**
*目标输出流
*/
privateOutputStreamstream;
/**
*表头
*/
privateMapfields;
/**
*数据源model所有字段map
*/
privatestaticMapfieldMap=newHashMap<>();
publicCSV(HttpServletResponseresponse,Mapfields,StringfileName,Class>clz)throwsIOException{
if(response==null||fields==null||fileName==null||clz==null)
thrownewIllegalArgumentException();
getFieldMap(clz,fieldMap);
this.stream=response.getOutputStream();
this.fields=fields;
response.setContentType("application/octet-stream;charset=GBK");
response.setHeader("Content-Disposition","attachment;fileName="+fileName);
//写表头,生成指定名字的文件,返回客户端
StringBuilderhb=newStringBuilder();
for(Entrye:fields.entrySet())
hb.append(e.getValue()+",");
stream.write(hb.substring(0,hb.length()-1).getBytes("GBK"));
stream.flush();
}
/**
*往表格中插入记录
*/
publicvoidwrite(List    
web开发中常见的准备Excel数据需要从数据库查询数据,或者跨系统调用接口查询数据,耗费大量时间,因此未及时向浏览器返回数据,导致504超时。
本工具使用ServletOutputStream分段的往浏览器flush数据。调用方式:先newCSV(),传入指定参数,不断的调用wirte()方法往浏览器写入数据,最后调用close方法关闭流。
本工具导出的文件格式为.csv文件,windowsoffice工具默认编码为ASCI,wps会匹配各种编码,libreOfficecalc可以指定编码,故此设置编码为GBK,兼容三种Excel软件,也可根据自身需求设置编码。
本工具只处理了CSV中”,”的转码,对于双引号并未处理。
希望本文能够对遇到此问题的朋友能有所帮助
