用poi导出excel时,当导出大量的数据时。会出现内存溢出的情况,后来查看api,poi3.8以后提供了一个新的工作薄:SXSSFWorkbook
能提供批量导出,但是SXSSFWorkbook导出的excel的文件的后缀要为“xlsx”:
//导出excel方法
public void write_Excel( String xls_write_Address,ArrayList<ArrayList> ls,String[] sheetnames) throws IOException {
FileOutputStream output = new FileOutputStream(new File(xls_write_Address)); //读取的文件路径
SXSSFWorkbook wb = new SXSSFWorkbook(10000);//内存中保留 10000 条数据,以免内存溢出,其余写入 硬盘
for(int sn=0;sn<ls.size();sn++){
Sheet sheet = wb.createSheet(String.valueOf(sn));
wb.setSheetName(sn, sheetnames[sn]);
ArrayList<String[]> ls2 = ls.get(sn);
for(int i=0;i<ls2.size();i++){
Row row = sheet.createRow(i);
String[] s = ls2.get(i);
for(int cols=0;cols<s.length;cols++){
Cell cell = row.createCell(cols);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);//文本格式
sheet.setColumnWidth(cols, s[cols].length()*384); //设置单元格宽度
cell.setCellValue(s[cols]);//写入内容
}
}
}
wb.write(output);
output.flush();
output.close();
}
//测试所用数据
public void test(){
String xls_add = "e:/st.xlsx";
String[] sheetName = {"id","name","age","kemu","score"};
ArrayList<ArrayList> ls = new ArrayList<ArrayList>();
ArrayList<String[]> arr1 = new ArrayList<String[]>();
for(int i=0;i<200000;i++){
String[] s={"aa"+i,"bb"+i,"cc"+i,"dd"+i,"dd"+i};
arr1.add(s);
}
ls.add(arr1);
try {
write_Excel(xls_add,ls,sheetName);
} catch (IOException e) {
e.printStackTrace();
}
}
//mian函数
public static void main(String[] args) {
ExpExcel ex = new ExpExcel();
ex.test();
}