首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

透过流的方式写入excel文件

2012-09-03 
通过流的方式写入excel文件我们在导入excel时候,通常会大批量数据导入,但是容易发生Exception in thread

通过流的方式写入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;?
??? }?

?

注意:表头部分和数据部分的间隔一定要用'\t?' 如果改用','号则导出文件用excel打开展示会有问题.

?

1 楼 蓝色0度 2012-05-02   你好,请问这种形式可以支持多sheet页的写入吗??
盼回~
谢谢:) 2 楼 pacer123 2012-05-04   如果数据流不大,就不需要通过流的方式去写excel.

热点排行