我们在导入excel时候,通常会大批量数据导入,但是容易发生Exception in thread "main" java.lang.OutOfMemoryError: Java heap space的内存溢出.
通常写法大致如下:
//定义sheet以及workbook对象部分略
FileOutputStream fos = new FileOutputStream("D://test//test0215.xlsx");
for (int i = 0; i < 100000; i++) {
sheet.createRow(i).createCell(0).setCellValue(1);
}
可以修改此导出方式,仅仅通过流的方式写入文件,可以避免创建大批量的对象时内存溢出.代码如下可以作为参考:
public static boolean createExcelFileByStream(String path, List list) {
try {
//定义表头
String userxlsinfo = "序号\t用户ID\t姓名\t手机\t留言信息";
File file = new File("c:\\streamExcel.xls");
if (file.isFile()) {
file.mkdir();
}
FileOutputStream out = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(out, "GB2312");
BufferedWriter bw = new BufferedWriter(osw);
// 创建表头
String sheader = userxlsinfo;
sheader += "\r\n";
bw.write(sheader);
if (list != null) {
// List list 此处可以遍历list对象
for (int i = 0; i < 5; i++) {
StringBuffer mess = new StringBuffer();
// 用户信息
mess.append((i + 1) + "\t");
mess.append((i + 1) + "\t");
mess.append((i + 1) + "\t");
mess.append((i + 1) + "\t");
mess.append((i + 1) + "\t");
mess.append("\r\n");
System.out.println(i);
bw.write(mess.toString());
}
}
bw.close();
osw.close();
out.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}