[JAVA] Avoid Zip bomb errors when reading large files with POI

Implementation of the problem

    OPCPackage p = null;
	try {
		p = OPCPackage.open(file, PackageAccess.READ);
		log.info("Read File:[" + file + "]");
		XSSFStringsTable strings = new XSSFStringsTable(p);
		XSSFReader xssfReader = new XSSFReader(p);
		StylesTable styles = xssfReader.getStylesTable();
		XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
		List<CommonRecord> resultList = new ArrayList<CommonRecord>();

		List<String> targetSheetList = ConfigUtil.getTargetSheet(key);
		while (iter.hasNext()) {
			InputStream stream = iter.next();
			String sheetName = iter.getSheetName();
			if (targetSheetList.isEmpty()
					|| !targetSheetList.isEmpty() && targetSheetList.contains(sheetName.trim())) {
				log.info("Read Sheet:[" + sheetName + "]");
				resultList.addAll(processSheet(styles, strings, stream, key, file));
			}
			stream.close();
		}
		return resultList;

StylesTable styles = xssfReader.getStylesTable (); The following error occurs.

java.lang.ClassCastException: org.apache.poi.xssf.usermodel.XSSFWorkbook cannot be cast to org.apache.poi.xssf.streaming.SXSSFWorkbook

Avoid errors by calling ZipSecureFile.setMinInflateRatio ()

Implementation after refurbishment

    OPCPackage p = null;
	try {
		p = OPCPackage.open(file, PackageAccess.READ);
		log.info("Read File:[" + file + "]");
		XSSFStringsTable strings = new XSSFStringsTable(p);
		XSSFReader xssfReader = new XSSFReader(p);
		StylesTable styles = xssfReader.getStylesTable();
		XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
		List<CommonRecord> resultList = new ArrayList<CommonRecord>();

		List<String> targetSheetList = ConfigUtil.getTargetSheet(key);
		while (iter.hasNext()) {
			InputStream stream = iter.next();
			String sheetName = iter.getSheetName();
			if (targetSheetList.isEmpty()
					|| !targetSheetList.isEmpty() && targetSheetList.contains(sheetName.trim())) {
				log.info("Read Sheet:[" + sheetName + "]");
				resultList.addAll(processSheet(styles, strings, stream, key, file));
			}
			stream.close();
		}
		return resultList;

Recommended Posts

Avoid Zip bomb errors when reading large files with POI
I want to avoid OutOfMemory when outputting large files with POI
Convert large XLSX files to CSV with Apache POI
To avoid errors when starting miChecker
Download large files with Apache JMeter
[Java] Reading and writing files with OpenCSV