org.apache.poi.openxml4j.opc.PackageAccess Java Examples

The following examples show how to use org.apache.poi.openxml4j.opc.PackageAccess. 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: XlsxSaxAnalyser.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
private OPCPackage readOpcPackage(XlsxReadWorkbookHolder xlsxReadWorkbookHolder, InputStream decryptedStream)
    throws Exception {
    if (decryptedStream == null && xlsxReadWorkbookHolder.getFile() != null) {
        return OPCPackage.open(xlsxReadWorkbookHolder.getFile());
    }
    if (xlsxReadWorkbookHolder.getMandatoryUseInputStream()) {
        if (decryptedStream != null) {
            return OPCPackage.open(decryptedStream);
        } else {
            return OPCPackage.open(xlsxReadWorkbookHolder.getInputStream());
        }
    }
    File readTempFile = FileUtils.createCacheTmpFile();
    xlsxReadWorkbookHolder.setTempFile(readTempFile);
    File tempFile = new File(readTempFile.getPath(), UUID.randomUUID().toString() + ".xlsx");
    if (decryptedStream != null) {
        FileUtils.writeToFile(tempFile, decryptedStream);
    } else {
        FileUtils.writeToFile(tempFile, xlsxReadWorkbookHolder.getInputStream());
    }
    return OPCPackage.open(tempFile, PackageAccess.READ);
}
 
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: 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 #4
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 #5
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 #6
Source File: ReaderUtil.java    From zerocell with Apache License 2.0 6 votes vote down vote up
/**
 * Reads a list of POJOs from the given excel file.
 *
 * @param path Excel file to read from
 * @param sheetName The sheet to extract from in the workbook
 * @param reader The reader class to use to load the file from the sheet
 */
public static void process(String path, String sheetName, ZeroCellReader reader) {
    if (path == null || path.trim().isEmpty()) {
        throw new IllegalArgumentException("'path' must be given");
    }

    File file = new File(path);
    if (file.exists() && file.isDirectory()) {
        throw new IllegalArgumentException("path must not be a directory");
    }
    try (OPCPackage opcPackage = OPCPackage.open(file.getAbsolutePath(), PackageAccess.READ)) {
        process(opcPackage, sheetName, reader);
    } catch(InvalidFormatException | EmptyFileException | NotOfficeXmlFileException ife) {
        throw new ZeroCellException(ERROR_NOT_OPENXML);
    } catch (IOException ioe) {
        throw new ZeroCellException("Failed to process file", ioe);
    }
}
 
Example #7
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 #8
Source File: ExcelReader.java    From excelReader with MIT License 5 votes vote down vote up
private static OPCPackage getOPCPackage(File file) throws Exception {
  if (null == file || !file.canRead()) {
    throw new Exception("File object is null or cannot have read permission");
  }

  return OPCPackage.open(file, PackageAccess.READ);
}
 
Example #9
Source File: BufferedStringsTableTest.java    From excel-streaming-reader with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies a bug where BufferedStringsTable was dropping text enclosed in formatting
 * instructions.
 */
@Test
public void testStringsWrappedInFormatting() throws Exception {
  File file = new File("src/test/resources/shared_styled_string.xlsx");
  File sstCache = File.createTempFile("cache", ".sst");
  sstCache.deleteOnExit();
  try (OPCPackage pkg = OPCPackage.open(file, PackageAccess.READ);
       BufferedStringsTable sst = BufferedStringsTable.getSharedStringsTable(sstCache, 1000, pkg)) {
    assertNotNull(sst);
    assertEquals("shared styled string", sst.getItemAt(0).getString());
  }
}
 
Example #10
Source File: BufferedStringsTableTest.java    From excel-streaming-reader with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies a bug where BufferedStringsTable was only looking at the first Characters xml element
 * in a text sequence.
 */
@Test
public void testStringsWithMultipleXmlElements() throws Exception {
  File file = new File("src/test/resources/blank_cells.xlsx");
  File sstCache = File.createTempFile("cache", ".sst");
  sstCache.deleteOnExit();
  try (OPCPackage pkg = OPCPackage.open(file, PackageAccess.READ);
       BufferedStringsTable sst = BufferedStringsTable.getSharedStringsTable(sstCache, 1000, pkg)) {
    assertNotNull(sst);
    assertEquals("B1 is Blank --->", sst.getEntryAt(0).getT());
    assertEquals("B1 is Blank --->", sst.getItemAt(0).getString());
  }
}
 
Example #11
Source File: ReaderUtil.java    From zerocell with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a list of POJOs from the given excel file.
 *
 * @param file Excel file to read from
 * @param sheetName The sheet to extract from in the workbook
 * @param reader The reader class to use to load the file from the sheet
 */
public static void process(File file, String sheetName, ZeroCellReader reader) {
    try (OPCPackage opcPackage = OPCPackage.open(file, PackageAccess.READ)) {
        process(opcPackage, sheetName, reader);
    } catch(InvalidFormatException | EmptyFileException | NotOfficeXmlFileException ife) {
        throw new ZeroCellException(ERROR_NOT_OPENXML);
    } catch (IOException ioe) {
        throw new ZeroCellException("Failed to process file", ioe);
    }
}
 
Example #12
Source File: FileExportUtil.java    From myexcel with Apache License 2.0 5 votes vote down vote up
/**
 * 加密导出
 *
 * @param workbook workbook
 * @param file     file
 * @param password password
 * @throws Exception Exception
 */
public static void encryptExport(final Workbook workbook, File file, final String password) throws Exception {
    if (workbook instanceof HSSFWorkbook) {
        throw new IllegalArgumentException("Document encryption for.xls is not supported");
    }
    String suffix = Constants.XLSX;
    if (!file.getName().endsWith(suffix)) {
        file = Paths.get(file.getAbsolutePath() + suffix).toFile();
    }
    try (FileOutputStream fos = new FileOutputStream(file)) {
        workbook.write(fos);
        if (workbook instanceof SXSSFWorkbook) {
            ((SXSSFWorkbook) workbook).dispose();
        }

        final POIFSFileSystem fs = new POIFSFileSystem();
        final EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
        final Encryptor enc = info.getEncryptor();
        enc.confirmPassword(password);

        try (OPCPackage opc = OPCPackage.open(file, PackageAccess.READ_WRITE);
             OutputStream os = enc.getDataStream(fs)) {
            opc.save(os);
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
            fs.writeFilesystem(fileOutputStream);
        }
    } finally {
        workbook.close();
    }
}
 
Example #13
Source File: AttachmentExportUtil.java    From myexcel with Apache License 2.0 5 votes vote down vote up
/**
 * 加密导出
 *
 * @param workbook workbook
 * @param fileName fileName
 * @param response response
 * @param password password
 */
public static void encryptExport(final Workbook workbook, String fileName, HttpServletResponse response, final String password) {
    if (workbook instanceof HSSFWorkbook) {
        throw new IllegalArgumentException("Document encryption for.xls is not supported");
    }
    Path path = null;
    try {
        String suffix = Constants.XLSX;
        path = TempFileOperator.createTempFile("encrypt_temp", suffix);
        workbook.write(Files.newOutputStream(path));

        final POIFSFileSystem fs = new POIFSFileSystem();
        final EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
        final Encryptor enc = info.getEncryptor();
        enc.confirmPassword(password);

        try (OPCPackage opc = OPCPackage.open(path.toFile(), PackageAccess.READ_WRITE);
             OutputStream os = enc.getDataStream(fs)) {
            opc.save(os);
        }
        if (!fileName.endsWith(suffix)) {
            fileName += suffix;
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        setAttachmentConfig(fileName, response);
        fs.writeFilesystem(response.getOutputStream());
    } catch (IOException | InvalidFormatException | GeneralSecurityException e) {
        throw new RuntimeException(e);
    } finally {
        clear(workbook);
        TempFileOperator.deleteTempFile(path);
    }
}
 
Example #14
Source File: HSSFPropertyFile.java    From poiji with MIT License 5 votes vote down vote up
@Override
public <T> T returnFromExcelFile(Class<T> type) {
    try (OPCPackage open = OPCPackage.open(file, PackageAccess.READ)) {
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(open);
        PropertyHandler propertyHandler = new PropertyHandler();
        return propertyHandler.unmarshal(type, xssfWorkbook.getProperties());
    } catch (IOException | OpenXML4JException e) {
        throw new PoijiException("Problem occurred while reading data", e);
    }
}
 
Example #15
Source File: XSSFUnmarshallerFile.java    From poiji with MIT License 5 votes vote down vote up
@Override
public <T> void returnFromExcelFile(Class<T> type, Consumer<? super T> consumer) {

    try (OPCPackage open = OPCPackage.open(poijiFile.file(), PackageAccess.READ)) {

        unmarshal0(type, consumer, open);

    } catch (ParserConfigurationException | SAXException | IOException | OpenXML4JException e) {
        throw new PoijiException("Problem occurred while reading data", e);
    }
}
 
Example #16
Source File: XLSX2CSV.java    From bdf3 with Apache License 2.0 4 votes vote down vote up
public XLSX2CSV(String inputFilePath, String outputFilePath) throws Exception {
    xlsxPackage = OPCPackage.open(inputFilePath, PackageAccess.READ);
    output = new PrintStream(outputFilePath, OUTPUT_CHARSET);
    minColumns = -1;
}
 
Example #17
Source File: XLSX2CSV.java    From DBus with Apache License 2.0 4 votes vote down vote up
public XLSX2CSV(String inputFilePath, String outputFilePath) throws Exception {
    xlsxPackage = OPCPackage.open(inputFilePath, PackageAccess.READ);
    output = new PrintStream(outputFilePath, OUTPUT_CHARSET);
    minColumns = -1;
}
 
Example #18
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();
}