Java Code Examples for org.apache.poi.openxml4j.opc.OPCPackage#close()

The following examples show how to use org.apache.poi.openxml4j.opc.OPCPackage#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WriteContextImpl.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
private POIFSFileSystem openFileSystemAndEncrypt(File file) throws Exception {
    POIFSFileSystem fileSystem = new POIFSFileSystem();
    Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor();
    encryptor.confirmPassword(writeWorkbookHolder.getPassword());
    OPCPackage opcPackage = null;
    try {
        opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE);
        OutputStream outputStream = encryptor.getDataStream(fileSystem);
        opcPackage.save(outputStream);
    } finally {
        if (opcPackage != null) {
            opcPackage.close();
        }
    }
    return fileSystem;
}
 
Example 2
Source File: Poi3Test.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
@Test
public void Encryption() throws Exception {
    String file = TestFileUtil.getPath() + "large" + File.separator + "large07.xlsx";
    POIFSFileSystem fs = new POIFSFileSystem();
    EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
    Encryptor enc = info.getEncryptor();
    enc.confirmPassword("foobaa");
    OPCPackage opc = OPCPackage.open(new File(file), PackageAccess.READ_WRITE);
    OutputStream os = enc.getDataStream(fs);
    opc.save(os);
    opc.close();

    // Write out the encrypted version
    FileOutputStream fos = new FileOutputStream("D:\\test\\99999999999.xlsx");
    fs.writeFilesystem(fos);
    fos.close();
    fs.close();

}
 
Example 3
Source File: Xlsx2TmxHelper.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
public void parseXlsxFileAndWriteTmxBody(String fileName, AbstractWriter tmxWriter, IProgressMonitor monitor)
		throws ParserConfigurationException, SAXException, IOException, OpenXML4JException {
	this.tmxWriter = tmxWriter;
	this.monitor = monitor;
	File file = new File(fileName);
	long length = file.length();
	monitor.beginTask("", countTotal(length));
	OPCPackage p = OPCPackage.open(fileName, PackageAccess.READ);
	ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(p);
	XSSFReader xssfReader = new XSSFReader(p);
	XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
	try {
		while (iter.hasNext()) {
			InputStream stream = iter.next();
			parse(stream, strings, tmxWriter);
			stream.close();
			// 目前只处理第一个sheet
			break;
		}
	} finally {
		p.close();
	}

	monitor.done();
}
 
Example 4
Source File: XlsxRowReader.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
public void readRows(IProgressMonitor monitor) throws ParserConfigurationException, SAXException, IOException, OpenXML4JException {
	monitor.beginTask("", 10);
	monitor.worked(1);
	OPCPackage p = OPCPackage.open(xlsxFile, PackageAccess.READ);
	ReadOnlySharedStringsTable shareString = new ReadOnlySharedStringsTable(p);
	XSSFReader xssfReader = new XSSFReader(p);
	XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
	try {
		while (iter.hasNext()) {
			InputStream stream = iter.next();
			readCells(stream, shareString, new SubProgressMonitor(monitor, 9));
			stream.close();
			// 目前只处理第一个sheet
			break;
		}
	} finally {
		p.close();
		monitor.done();
	}
}
 
Example 5
Source File: Xlsx2TmxHelper.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
public void parseXlsxFileAndWriteTmxBody(String fileName, AbstractWriter tmxWriter, IProgressMonitor monitor)
		throws ParserConfigurationException, SAXException, IOException, OpenXML4JException {
	this.tmxWriter = tmxWriter;
	this.monitor = monitor;
	File file = new File(fileName);
	long length = file.length();
	monitor.beginTask("", countTotal(length));
	OPCPackage p = OPCPackage.open(fileName, PackageAccess.READ);
	ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(p);
	XSSFReader xssfReader = new XSSFReader(p);
	XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
	try {
		while (iter.hasNext()) {
			InputStream stream = iter.next();
			parse(stream, strings, tmxWriter);
			stream.close();
			// 目前只处理第一个sheet
			break;
		}
	} finally {
		p.close();
	}

	monitor.done();
}
 
Example 6
Source File: XlsxHandler.java    From easyexcel with Apache License 2.0 5 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename
 * @throws IOException
 * @throws OpenXML4JException
 * @throws SAXException
 * @throws Exception
 */
public void process(String filename) throws IOException, OpenXML4JException, SAXException {
    OPCPackage pkg = null;
    try {
	    pkg = OPCPackage.open(filename);
        XSSFReader xssfReader = new XSSFReader(pkg);
        stylesTable = xssfReader.getStylesTable();
        SharedStringsTable sst = xssfReader.getSharedStringsTable();
        XMLReader parser = this.fetchSheetParser(sst);
        Iterator<InputStream> sheets = xssfReader.getSheetsData();
   		while (sheets.hasNext()) {
   			currRowIndex = 0;
   			sheetIndex++;
   			InputStream sheet = null;
   			try {
   			    sheet = sheets.next();
   			    InputSource sheetSource = new InputSource(sheet);
   			    parser.parse(sheetSource);
   			} finally {
   			    sheet.close();
               }
   		}
   		while (!context.fileEnd());
	} finally {
           pkg.close();
       }
}
 
Example 7
Source File: MSExcelOOXMLSignUtil.java    From hadoopoffice with Apache License 2.0 5 votes vote down vote up
private void signUnencryptedOpcPackage(InputStream tmpFileInputStream, SignatureConfig sc) throws InvalidFormatException, IOException, XMLSignatureException, MarshalException {
	OPCPackage	pkg = OPCPackage.open(tmpFileInputStream);
	sc.setOpcPackage(pkg);
	// needed to avoid linebreaks for xmlsec
	String originalPropertyValue=null;

		
		SignatureInfo si = new SignatureInfo();
		si.setSignatureConfig(sc);
		si.confirmSignature();
		pkg.save(this.finalOutputStream);
		pkg.close();
}
 
Example 8
Source File: MSExcelOOXMLSignUtil.java    From hadoopoffice with Apache License 2.0 5 votes vote down vote up
private void signEncryptedPackage(InputStream tmpFileInputStream, SignatureConfig sc, String password) throws IOException, InvalidFormatException, FormatNotUnderstoodException, XMLSignatureException, MarshalException {

	POIFSFileSystem poifsTemp = new POIFSFileSystem(tmpFileInputStream);
	EncryptionInfo info = new EncryptionInfo(poifsTemp);
	Decryptor d = Decryptor.getInstance(info);

	try {
		if (!d.verifyPassword(password)) {
			throw new FormatNotUnderstoodException("Error: Cannot decrypt new Excel file (.xlsx) for signing. Invalid password");
		}
		// signing
		OPCPackage pkg = OPCPackage.open(d.getDataStream(poifsTemp));
		sc.setOpcPackage(pkg);
		
		SignatureInfo si = new SignatureInfo();
		si.setSignatureConfig(sc);
		si.confirmSignature();
		// encrypt again
		Encryptor enc = info.getEncryptor();
		enc.confirmPassword(password);
		POIFSFileSystem poifs = new POIFSFileSystem();
		OutputStream os = enc.getDataStream(poifs);
		pkg.save(os);
		pkg.close();
		if (os!=null) {
			os.close();
		}
		poifs.writeFilesystem(this.finalOutputStream);
		if (poifs!=null) {
			poifs.close();
		}
		if (poifsTemp!=null) {
			poifsTemp.close();
		}
	} catch (GeneralSecurityException e) {
		
		LOG.error(e);
		throw new FormatNotUnderstoodException("Error: Cannot decrypt new Excel file (.xlsx)  for signing.");
	} 
}
 
Example 9
Source File: OOXMLThumbnailContentTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void transformInternal(ContentReader reader,
                                 ContentWriter writer,
                                 TransformationOptions options) throws Exception
{
    final String sourceMimetype = reader.getMimetype();
    final String sourceExtension = getMimetypeService().getExtension(sourceMimetype);
    final String targetMimetype = writer.getMimetype();
    
    
    if (log.isDebugEnabled())
    {
        StringBuilder msg = new StringBuilder();
        msg.append("Transforming from ").append(sourceMimetype)
           .append(" to ").append(targetMimetype);
        log.debug(msg.toString());
    }
    
    
    OPCPackage pkg = null;
    try 
    {
        File ooxmlTempFile = TempFileProvider.createTempFile(this.getClass().getSimpleName() + "_ooxml", sourceExtension);
        reader.getContent(ooxmlTempFile);
        
        // Load the file
        pkg = OPCPackage.open(ooxmlTempFile.getPath());
        
        // Does it have a thumbnail?
        PackageRelationshipCollection rels = 
            pkg.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL);
        if (rels.size() > 0)
        {
            // Get the thumbnail part
            PackageRelationship tRel = rels.getRelationship(0);
            PackagePart tPart = pkg.getPart(tRel);
            
            // Write it to the target
            InputStream tStream = tPart.getInputStream();
            writer.putContent( tStream );
            tStream.close();
        }
        else
        {
            log.debug("No thumbnail present in " + reader.toString());
            throw new UnimportantTransformException(NO_THUMBNAIL_PRESENT_IN_FILE + targetMimetype);
        }
    } 
    catch (IOException e) 
    {
       throw new AlfrescoRuntimeException("Unable to transform " + sourceExtension + " file.", e);
    }
    finally
    {
        if (pkg != null)
        {
            pkg.close();
        }
    }
}
 
Example 10
Source File: StreamingReaderTest.java    From excel-streaming-reader with Apache License 2.0 4 votes vote down vote up
@Test
public void testClosingFiles() throws Exception {
  OPCPackage o = OPCPackage.open(new File("src/test/resources/blank_cell_StringCellValue.xlsx"), PackageAccess.READ);
  o.close();
}
 
Example 11
Source File: ExcelWorkSheetHandlerTest.java    From excelReader with MIT License 4 votes vote down vote up
/**
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
  String SAMPLE_PERSON_DATA_FILE_PATH = "src/test/resources/Sample-Person-Data.xlsx";

  // Input File initialize
  File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
  InputStream inputStream = new FileInputStream(file);

  // Excel Cell Mapping
  Map<String, String> cellMapping = new HashMap<String, String>();
  cellMapping.put("HEADER", "Person Id,Name,Height,Email Address,DOB,Salary");
  cellMapping.put("A", "personId");
  cellMapping.put("B", "name");
  cellMapping.put("C", "height");
  cellMapping.put("D", "emailId");
  cellMapping.put("E", "dob");
  cellMapping.put("F", "salary");

  // The package open is instantaneous, as it should be.
  OPCPackage pkg = null;
  try {

    ExcelWorkSheetHandler<PersonVO> workSheetHandler =
        new ExcelWorkSheetHandler<PersonVO>(PersonVO.class, cellMapping);

    pkg = OPCPackage.open(inputStream);

    ExcelSheetCallback sheetCallback = new ExcelSheetCallback() {
      private int sheetNumber = 0;

      @Override
      public void startSheet(int sheetNum, String sheetName) {
        this.sheetNumber = sheetNum;
        System.out.println("Started processing sheet number=" + sheetNumber
            + " and Sheet Name is '" + sheetName + "'");
      }

      @Override
      public void endSheet() {
        System.out.println("Processing completed for sheet number=" + sheetNumber);
      }
    };

    System.out.println("Constructor: pkg, workSheetHandler, sheetCallback");
    ExcelReader example1 = new ExcelReader(pkg, workSheetHandler, sheetCallback);
    example1.process();

    if (workSheetHandler.getValueList().isEmpty()) {
      // No data present
      LOG.error("sHandler.getValueList() is empty");
    } else {

      LOG.info(workSheetHandler.getValueList().size()
          + " no. of records read from given excel worksheet successfully.");

      // Displaying data ead from Excel file
      displayPersonList(workSheetHandler.getValueList());
    }

    System.out.println("\nConstructor: filePath, workSheetHandler, sheetCallback");
    ExcelReader example2 =
        new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, workSheetHandler, sheetCallback);
    example2.process();

    System.out.println("\nConstructor: file, workSheetHandler, sheetCallback");
    ExcelReader example3 = new ExcelReader(file, workSheetHandler, null);
    example3.process();

  } catch (RuntimeException are) {
    LOG.error(are.getMessage(), are.getCause());
  } catch (InvalidFormatException ife) {
    LOG.error(ife.getMessage(), ife.getCause());
  } catch (IOException ioe) {
    LOG.error(ioe.getMessage(), ioe.getCause());
  } finally {
    IOUtils.closeQuietly(inputStream);
    try {
      if (null != pkg) {
        pkg.close();
      }
    } catch (IOException e) {
      // just ignore IO exception
    }
  }
}
 
Example 12
Source File: ExcelWorkSheetRowCallbackHandlerTest.java    From excelReader with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {

    String SAMPLE_PERSON_DATA_FILE_PATH = "src/test/resources/Sample-Person-Data.xlsx";

    File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
    InputStream inputStream = new FileInputStream(file);

    // The package open is instantaneous, as it should be.
    OPCPackage pkg = null;
    try {
      ExcelWorkSheetRowCallbackHandler sheetRowCallbackHandler =
          new ExcelWorkSheetRowCallbackHandler(new ExcelRowContentCallback() {

            @Override
            public void processRow(int rowNum, Map<String, String> map) {

              // Do any custom row processing here, such as save
              // to database
              // Convert map values, as necessary, to dates or
              // parse as currency, etc
              System.out.println("rowNum=" + rowNum + ", map=" + map);

            }

          });

      pkg = OPCPackage.open(inputStream);

      ExcelSheetCallback sheetCallback = new ExcelSheetCallback() {
        private int sheetNumber = 0;

        @Override
        public void startSheet(int sheetNum, String sheetName) {
          this.sheetNumber = sheetNum;
          System.out.println("Started processing sheet number=" + sheetNumber
              + " and Sheet Name is '" + sheetName + "'");
        }

        @Override
        public void endSheet() {
          System.out.println("Processing completed for sheet number=" + sheetNumber);
        }
      };

      System.out.println("Constructor: pkg, sheetRowCallbackHandler, sheetCallback");
      ExcelReader example1 = new ExcelReader(pkg, sheetRowCallbackHandler, sheetCallback);
      example1.process();

      System.out.println("\nConstructor: filePath, sheetRowCallbackHandler, sheetCallback");
      ExcelReader example2 =
          new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, sheetRowCallbackHandler, sheetCallback);
      example2.process();

      System.out.println("\nConstructor: file, sheetRowCallbackHandler, sheetCallback");
      ExcelReader example3 = new ExcelReader(file, sheetRowCallbackHandler, null);
      example3.process();

    } catch (RuntimeException are) {
      LOG.error(are.getMessage(), are.getCause());
    } catch (InvalidFormatException ife) {
      LOG.error(ife.getMessage(), ife.getCause());
    } catch (IOException ioe) {
      LOG.error(ioe.getMessage(), ioe.getCause());
    } finally {
      IOUtils.closeQuietly(inputStream);
      try {
        if (null != pkg) {
          pkg.close();
        }
      } catch (IOException e) {
        // just ignore IO exception
      }
    }
  }