/**
* When opening a workbook, either a .xls HSSFWorkbook, or a .xlsx
* XSSFWorkbook, the Workbook can be loaded from either a File or an
* InputStream. Using a File object allows for lower memory consumption,
* while an InputStream requires more memory as it has to buffer the
* whole file.
* new File会节省内存,new FileInputStream会占用较大内存
* If using WorkbookFactory, it's very easy to use one or the other:
*/
// 第一种读取方式 Use a file
Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));
//第二种读取方式 Use an InputStream, needs more memory
Workbook wb0 = WorkbookFactory.create(new FileInputStream(
"MyExcel.xlsx"));
/**
* If using HSSFWorkbook or XSSFWorkbook directly, you should generally
* go through NPOIFSFileSystem or OPCPackage, to have full control of
* the lifecycle (including closing the file when done):
* 如果直接用HSSFWorkbook or XSSFWorkbook ,你需要显式关闭文件
*/
//第三种读取方式 HSSFWorkbook, File
NPOIFSFileSystem fs = new NPOIFSFileSystem(new File("file.xls"));
HSSFWorkbook wb1 = new HSSFWorkbook(fs.getRoot(), true);
fs.close();
//第四种读取方式 HSSFWorkbook, InputStream, needs more memory
NPOIFSFileSystem fs1 = new NPOIFSFileSystem(new FileInputStream(
"MyExcel.xlsx"));
HSSFWorkbook wb2 = new HSSFWorkbook(fs.getRoot(), true);
//第五种读取方式 XSSFWorkbook, File
OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));
XSSFWorkbook wb3 = new XSSFWorkbook(pkg);
pkg.close();
//第六种读取方式 XSSFWorkbook, InputStream, needs more memory
OPCPackage pkg1 = OPCPackage.open(new FileInputStream("MyExcel.xlsx"));
XSSFWorkbook wb4 = new XSSFWorkbook(pkg);
pkg1.close();
总结:总共有6种方式创建读取的Excel对应,new File的方式较省内存,new InputStream的方式较耗内存
java POI读取Excel时Files 与 InputStreams两种方式的比较
最新推荐文章于 2024-07-20 16:41:24 发布