在实际项目中,经常会用到POI3.8来导出excel。而导出excel的时候,会因为残留大量以.xml结尾的文件而导致服务器存储空间急剧增长,最后导致系统挂了。为此,该怎么办呢?

.xml后缀残留文件示例

通过大量的翻阅资料,目前有两种解决方式:

方式1:手动清除临时文件

POI3.8并没有提供方法来清除临时文件,为此,这里可以自己手动进行清除:

    <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
package com.jack.shx.MySpringBoot;

import java.io.File;
import java.lang.reflect.Field;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.streaming.SheetDataWriter; public class SXSSFTempFilesDelete {
/***
* Returns a private attribute of a class
* @param containingClass The class that contains the private attribute to retrieve
* @param fieldToGet the name of the attribute to get
* @return The private attribute
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
public static Object getPrivateAttribute(
Object containingClass, String fieldToGet)
throws NoSuchFieldException, IllegalAccessException
{
// get the field of the containingClass instance
Field declaredField = containingClass.getClass().getDeclaredField(fieldToGet);
declaredField.setAccessible(true); // access it
Object get = declaredField.get(containingClass); // return it!
return get;
} /***
* Deletes all temporary files of the SXSSFWorkbook instance
* @param workbook
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
public static void deleteSXSSFTempFiles(SXSSFWorkbook workbook)
throws NoSuchFieldException, IllegalAccessException {
int numberOfSheets = workbook.getNumberOfSheets();
// iterate through all sheets (each sheet as a temp file)
for (int i = 0; i <= numberOfSheets; i++) {
Sheet sheetAt = workbook.getSheetAt(i);
// delete only if the sheet is written by stream
if (sheetAt instanceof SXSSFSheet) {
SheetDataWriter sdw = (SheetDataWriter) getPrivateAttribute(sheetAt, "_writer");
File f = (File) getPrivateAttribute(sdw, "_fd");
try {
f.delete();
} catch (Exception ex) {
// could not delete the file
}
}
}
}
}

或者

方式2:将POI3.8替换成更高的版本,并利用dispose方法清除临时文件

目前,更高版本的POI已经提供了清除临时文件的方法,具体可以参考官网:http://poi.apache.org/apidocs/org/apache/poi/xssf/streaming/SXSSFWorkbook.html

此时,我们在使用的时候就可以方便的清除临时文件,避免空间爆满了:

/**
* 大数据量导出
* @throws IOException
*/
@Test
public void text2() throws IOException { XSSFWorkbook xssfWorkbook = new XSSFWorkbook(Thread.currentThread().getContextClassLoader().getResourceAsStream("bigdata.xlsx"));
SXSSFWorkbook wb = new SXSSFWorkbook(xssfWorkbook, 1000); //内存中保留 1000 条数据,以免内存溢出,其余写入 硬盘  专门处理大数据 Sheet sh = wb.getSheetAt(0);
for(int rownum = 1; rownum < 75537; rownum++){
Row row = sh.createRow(rownum);
for(int cellnum = 0; cellnum < 10; cellnum++){
Cell cell = row.createCell(cellnum);
String address = new CellReference(cell).formatAsString();
cell.setCellValue(address);
} } // // Rows with rownum < 900 are flushed and not accessible
// for(int rownum = 0; rownum < 900; rownum++){
// Assert.assertNull(sh.getRow(rownum));
// }
//
// // ther last 100 rows are still in memory
// for(int rownum = 900; rownum < 1000; rownum++){
// Assert.assertNotNull(sh.getRow(rownum));
// } FileOutputStream out = new FileOutputStream("D:\\sxssf.xlsx");
wb.write(out);
out.close(); // dispose of temporary files backing this workbook on disk
wb.dispose();

请注意 就这个一句话    wb.dispose();

利用POi3.8导出excel产生大量xml临时文件怎么办?的更多相关文章

  1. Java利用POI导入导出Excel中的数据

         首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地 ...

  2. .net mvc利用NPOI导入导出excel

    1.导出Excel :首先引用NPOI包(Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> ...

  3. ASP.Net MVC利用NPOI导入导出Excel

    因近期项目遇到所以记录一下: 首先导出Excel: 首先引用NPOI包 http://pan.baidu.com/s/1i3Fosux (Action一定要用FileResult) /// <s ...

  4. net mvc 利用NPOI导入导出excel

    1.导出Excel : 首先引用NPOI包(Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> ...

  5. 海量数据Excel报表利器——EasyExcel(一 利用反射机制导出Excel)

    EasyExcel 写入(导出) 互联网的精髓就是共享,可以共享技术.共享经验.共享情感.共享快乐~ 很多年前就有这个想法了,从事IT行业时间也不短了,应该把自己工作和业余所学习的东西记录并分享出来, ...

  6. Springmvc和poi3.9导出excel并弹出下载框

    Springmvc 和 poi3.9 用java程序从数据库导出数据到excel(在博客园的第一篇原创博客) @RequestMapping(value = "/importexcel.ht ...

  7. .net利用NPOI导入导出Excel

    NPOI在.net中的操作Excel 1.读取 using (FileStream stream = new FileStream(@"c:\客户资料.xls", FileMode ...

  8. asp.net利用剪切板导出excel

    public enum ClipboardFormats : uint { CF_TEXT = 1, CF_BITMAP = 2, CF_METAFILEPICT = 3, CF_SYLK = 4, ...

  9. 导出excel(利用工具类导出excel)

    /** * 添加导出功能 * @param creditPageResult * @param request * @param response */ @RequestMapping(value = ...

随机推荐

  1. 【43.26%】【codeforces 732C】Sanatorium

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...

  2. Ubuntu 16.04安装MinGW32(在/etc/apt/sources.list里添加源)

    Ubuntu 16.04下直接使用命令安装MinGW32: sudo apt-get install mingw32   但是,会报错: Unable to locate package mingw3 ...

  3. jQuery多库共存处理$.noConflict()

    如果我们需要同时使用jQuery和其他JavaScript库,我们可以使用 $.noConflict()把$的控制权交给其他库.旧引用的$ 被保存在jQuery的初始化; noConflict() 简 ...

  4. Python Tricks(二十一)—— 排列组合的计算

    使用循环: 阶乘的实现: def fac(n): r = 1. for i in range(1, n+1): r *= i return r 排列:Anm=m!n!=(m−n+1)⋯m def pe ...

  5. Exception: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams

    RelativeLayout title_bg = (RelativeLayout)FTU_Bluetooth.this.findViewById(R.id.titlebar); LinearLayo ...

  6. android4.4系统解决“ERRORcouldn&#39;t find native method”方法

    android4.4系统解决"ERRORcouldn't find native method"方法 今天笔者在移植一个tv模块从android4.2到android4.4系统的设 ...

  7. Linux性能测试 KSysguard工具

    KDE System Guard (KSysguard)是KDE的任务管理和性能监控工具.它采用client/server架构,可以监控本机也可以监控远端主机. KDE System Guard默认的 ...

  8. 代码首要的目标应该是“解决问题”(包括“没有 bug”),其次的目标才是“简单优雅”。

    什么是现实理想主义者 曾经有人看了我的文章,以为我是一个“理想主义者”,来找我聊天.他说:“你知道吗,我跟你一样喜欢简单优雅的代码.上次我在某公司工作,看到他们的代码乱得不成样子,二话没说给他们重写了 ...

  9. Oracle 已有则更新,没有则插入

    使用merge merge into 表名 t1 using (select '数据数据' 字段1,'数据数据' 字段2 from dual) t2 on (t1.字段1 = t2.字段1) when ...

  10. ABP框架——单表实体流程

    实体实体配置文件菜单本地化语言:xml文件权限配置领域服务应用层CRUDDTOSPA路由:app.js视图生成:.html,.js