Java导出csv格式,百万数据

尘同学 尘同学 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我遇到的问题是:导出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();
}
}
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
尘同学
Java EE 67,535 成员 225,843 内容