通过流的方式写入excel文件

我们在导入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;  
    } 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值