Java导出csv格式,百万数据

尘同学 2016-11-28 05:04:14
我遇到的问题是:导出csv格式的报内存溢出错误,数据量小没问题,7万左右会出现问题,,看百度上说可以:导入csv格式的时候,写缓冲区什么的,可我不是很明白怎么写,没搜到想要的答案,所以想请大家帮忙了,谢谢了啊
下面是我的代码
public class ExportUtil {

/**
* 导出成CSV TXT resultData中每个是一行数据。
*
* @param out
* @param colTitleList
* 标题
* @param resultData
* 数据。
* @throws Exception
* String title,String[] rowName,List<Object[]> dataList
*/
public static void writeCSV(HttpServletResponse response, String title,
String[] colTitleList, List<Object[]> resultData) throws Exception {
System.out.println("writeCSV 方法进入 ");
DateFormat sdf2 = new SimpleDateFormat("yyyy-MM");
String dates = sdf2.format(new Date());
title = dates +title;

String downloadFileName = new String(title.getBytes("gbk"), "iso8859-1");
response.reset();
response.setHeader("Content-Disposition", "attachment;filename="
+ downloadFileName + ".csv");// 指定下载的文件名
response.setContentType("application/vnd.ms-excel");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
OutputStream output = response.getOutputStream();

if (resultData == null)
resultData = new ArrayList();
PrintWriter pw = null;
pw = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(
output, 1024), "GBK"));

if (colTitleList != null) {// 写标题
for (int i = 0; i < colTitleList.length; i++) {
String outValue = String.valueOf(colTitleList[i]);
pw.print(outValue);
if (i != colTitleList.length - 1)
pw.print(",");
}
pw.println();
}

for (int i = 0; i < resultData.size(); i++) {
/* ArrayList rowData = (ArrayList)resultData.get(i); */
Object[] rowData = resultData.get(i);// 遍历每个对象
for (int j = 0; j < rowData.length; j++) {
String value = null;
if (!"".equals(rowData[j]) && rowData[j] != null) {
value = rowData[j].toString();
pw.print("\"" + value.replace("\"", "\"\"") + "\"");
}

if (j != rowData.length - 1)
pw.print(",");
}
pw.println();
}
pw.close();
output.close();
}
}
...全文
727 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
snowwhite211 2019-06-18
  • 打赏
  • 举报
回复
楼主请问导出一百万CSV数据没问题吗
尘同学 2016-11-29
  • 打赏
  • 举报
回复
PrintWriter pw = null; pw = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream( output, 1024), "GBK")); 我后来变成了 PrintWriter pw = null; pw = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream( output,1024), "GBK"),true);//这里的ture表示流会自动刷新,在后面可以不用使用flush()方法 然后可以了,谢谢你的回答,谢谢了
tianfang 2016-11-28
  • 打赏
  • 举报
回复
把需求描述清楚,是导出到文件,还是http输出? 看代码象是http输出,但要写在doGet,doPost方法中

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧