List of usage examples for org.apache.poi.openxml4j.opc OPCPackage open
public static OPCPackage open(InputStream in) throws InvalidFormatException, IOException
From source file:com.github.poi.LoadPasswordProtectedXlsx.java
License:Apache License
public static void main(String[] args) { try {/*from w ww. j a v a 2s . c o m*/ if (args.length != 2) { throw new Exception("Expected 2 params: filename and password"); } XlsxUtils.checkTempFiles(); String filename = args[0]; String password = args[1]; try (FileInputStream fis = new FileInputStream(filename); InputStream unencryptedStream = XlsxUtils.decrypt(fis, password); AesZipFileZipEntrySource source = AesZipFileZipEntrySource .createZipEntrySource(unencryptedStream); OPCPackage pkg = OPCPackage.open(source); XSSFWorkbook workbook = new XSSFWorkbook(pkg)) { System.out.println("sheet count: " + workbook.getNumberOfSheets()); } XlsxUtils.checkTempFiles(); } catch (Throwable t) { t.printStackTrace(); } }
From source file:com.github.poi.LoadPasswordProtectedXlsxStreaming.java
License:Apache License
public static void main(String[] args) { try {/*from www.j av a2s .co m*/ if (args.length != 2) { throw new Exception("Expected 2 params: filename and password"); } XlsxUtils.checkTempFiles(); String filename = args[0]; String password = args[1]; try (FileInputStream fis = new FileInputStream(filename); InputStream unencryptedStream = XlsxUtils.decrypt(fis, password); AesZipFileZipEntrySource source = AesZipFileZipEntrySource .createZipEntrySource(unencryptedStream); OPCPackage pkg = OPCPackage.open(source)) { XSSFReader reader = new XSSFReader(pkg); SheetIterator iter = (SheetIterator) reader.getSheetsData(); int count = 0; while (iter.hasNext()) { iter.next(); count++; } System.out.println("sheet count: " + count); } XlsxUtils.checkTempFiles(); } catch (Throwable t) { t.printStackTrace(); } }
From source file:com.globalsight.util.ExcelUtil.java
License:Apache License
public static Workbook getWorkbook(String filename) { Workbook workbook = null;//w w w . ja va2 s . com if (StringUtil.isEmpty(filename) || !isExcel(filename)) return null; File file = null; try { file = new File(filename); if (!file.exists() || file.isDirectory()) return null; InputStream is = new FileInputStream(file); if (isXls(filename)) workbook = new HSSFWorkbook(is); else workbook = new XSSFWorkbook(OPCPackage.open(file)); } catch (Exception e) { logger.error("Cannot open Excel file correctly.", e); } return workbook; }
From source file:com.globalsight.util.ExcelUtil.java
License:Apache License
public static Workbook getWorkbook(String filename, InputStream is) { Workbook workbook = null;//from w ww.j a v a 2s . c o m if (StringUtil.isEmpty(filename) || !isExcel(filename) || is == null) return null; File file = null; try { file = new File(filename); if (!file.exists() || file.isDirectory()) return null; if (isXls(filename)) workbook = new HSSFWorkbook(is); else workbook = new XSSFWorkbook(OPCPackage.open(is)); } catch (Exception e) { logger.error("Cannot open Excel file correctly.", e); } return workbook; }
From source file:com.hauldata.dbpa.file.book.XlsxSourceBook.java
License:Apache License
@Override public void open() throws IOException { try {//from www . j a va 2 s . c om pkg = OPCPackage.open(new java.io.File(getName())); book = new XSSFWorkbook(pkg); } catch (InvalidFormatException ex) { throw new RuntimeException(ex.getMessage()); } }
From source file:com.joalgoca.validatorLayout.layoutDefinition.XLSXDocumentLayout.java
@Override public ResponseValidator validateDocument(InputStream inputStream) { ResponseValidator response;//from w ww . jav a 2 s .c om StringBuilder stringBuilder = new StringBuilder(); if (isReadyToValidate() && inputStream != null) { HashMap rowsType = new HashMap(); for (int i = 0; i < documentValidator.getListRowValidator().size(); i++) { rowsType.put(documentValidator.getListRowValidator().get(i).getName(), i); } try { int rownum = 0; int wrong = 0; int right = 0; int skip = 0; OPCPackage pkg = OPCPackage.open(inputStream); XSSFWorkbook workBook = new XSSFWorkbook(pkg); FormulaEvaluator evaluator = workBook.getCreationHelper().createFormulaEvaluator(); XSSFSheet xssfSheet = workBook.getSheetAt(0); for (Row row : xssfSheet) { String rowType = row.getCell(0).getStringCellValue(); if (rowsType.containsKey(rowType)) { RowValidator rowValidator = documentValidator.getListRowValidator() .get((int) rowsType.get(rowType)); int columnNum = rowValidator.getListItemValidator().size(); if (row.getLastCellNum() == columnNum) { String[] values = new String[columnNum]; int i = 0; for (Cell cell : row) { switch (evaluator.evaluateInCell(cell).getCellType()) { case Cell.CELL_TYPE_NUMERIC: values[i] = cell.getNumericCellValue() + ""; break; case Cell.CELL_TYPE_STRING: values[i] = cell.getStringCellValue(); break; case Cell.CELL_TYPE_FORMULA: values[i] = ""; break; case Cell.CELL_TYPE_BLANK: values[i] = ""; break; } i++; } ResponseValidator responseValidator = rowValidator.validate(values); if (!responseValidator.isSuccess()) { wrong++; stringBuilder.append("{\"row\":").append(rownum).append(",\"message\":") .append(responseValidator.getMessage()).append(","); } else right++; } else { wrong++; stringBuilder.append("{\"row\":").append(rownum) .append(",\"success\":false,\"message\":\"Line wrong size\"},").toString(); } } else { skip++; stringBuilder.append("{\"row\":").append(rownum) .append(",\"success\":false,\"message\":\"Unknow row type\"},").toString(); } rownum++; } response = new ResponseValidator(wrong == 0, "{\"skip\":" + skip + ",\"wrong\":" + wrong + ",\"right\":" + right + ",\"count\":" + rownum + ",\"errorMessages\":[" + (stringBuilder.toString().length() > 0 ? stringBuilder.substring(0, stringBuilder.toString().length() - 1) : "") + "]}"); } catch (Exception ex) { Logger.getLogger(FlatFixedDocumentLayout.class.getName()).log(Level.SEVERE, null, ex); response = new ResponseValidator(false, stringBuilder.append("\"success\":false,\"message\":\"") .append(ex.getMessage()).append("\"}").toString()); } finally { try { inputStream.close(); } catch (IOException ex) { response = new ResponseValidator(false, stringBuilder.append("\"success\":false,\"message\":\"") .append(ex.getMessage()).append("\"}").toString()); } } } else { response = new ResponseValidator(false, stringBuilder.append("\"success\":false,\"message\":\"No configuration loaded\"}").toString()); } return response; }
From source file:com.kplot.web.data.WorkbookFactory.java
License:Apache License
/** * Creates a Workbook from the given NPOIFSFileSystem, which may * be password protected/*from w ww . j av a 2 s . co m*/ * * @param fs The {@link NPOIFSFileSystem} to read the document from * @param password The password that should be used or null if no password is necessary. * * @return The created Workbook * * @throws IOException if an error occurs while reading the data * @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook} */ private static Workbook create(NPOIFSFileSystem fs, String password) throws IOException, InvalidFormatException { DirectoryNode root = fs.getRoot(); // Encrypted OOXML files go inside OLE2 containers, is this one? if (root.hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) { EncryptionInfo info = new EncryptionInfo(fs); Decryptor d = Decryptor.getInstance(info); boolean passwordCorrect = false; InputStream stream = null; try { if (password != null && d.verifyPassword(password)) { passwordCorrect = true; } if (!passwordCorrect && d.verifyPassword(Decryptor.DEFAULT_PASSWORD)) { passwordCorrect = true; } if (passwordCorrect) { stream = d.getDataStream(root); } } catch (GeneralSecurityException e) { throw new IOException(e); } if (!passwordCorrect) { if (password != null) throw new EncryptedDocumentException("Password incorrect"); else throw new EncryptedDocumentException( "The supplied spreadsheet is protected, but no password was supplied"); } OPCPackage pkg = OPCPackage.open(stream); return create(pkg); } // If we get here, it isn't an encrypted XLSX file // So, treat it as a regular HSSF XLS one if (password != null) { Biff8EncryptionKey.setCurrentUserPassword(password); } try { return new HSSFWorkbook(root, true); } finally { Biff8EncryptionKey.setCurrentUserPassword(null); } }
From source file:com.kplot.web.data.WorkbookFactory.java
License:Apache License
/** * Creates the appropriate HSSFWorkbook / XSSFWorkbook from * the given InputStream, which may be password protected. * <p>Your input stream MUST either support mark/reset, or * be wrapped as a {@link PushbackInputStream}! Note that * using an {@link InputStream} has a higher memory footprint * than using a {@link File}.</p> * * <p>Note that in order to properly release resources the * Workbook should be closed after use. Note also that loading * from an InputStream requires more memory than loading * from a File, so prefer {@link #create(File)} where possible.</p> * * @param inp The {@link InputStream} to read data from. * @param password The password that should be used or null if no password is necessary. * * @return The created Workbook/*from w w w . j a v a 2 s. c o m*/ * * @throws IOException if an error occurs while reading the data * @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook} * @throws EncryptedDocumentException If the wrong password is given for a protected file * @throws EmptyFileException If an empty stream is given */ public static Workbook create(InputStream inp, String password) throws IOException, InvalidFormatException, EncryptedDocumentException { // If clearly doesn't do mark/reset, wrap up if (!inp.markSupported()) { inp = new PushbackInputStream(inp, 8); } // Ensure that there is at least some data there byte[] header8 = IOUtils.peekFirst8Bytes(inp); // Try to create if (NPOIFSFileSystem.hasPOIFSHeader(header8)) { NPOIFSFileSystem fs = new NPOIFSFileSystem(inp); return create(fs, password); } if (POIXMLDocument.hasOOXMLHeader(inp)) { return new XSSFWorkbook(OPCPackage.open(inp)); } throw new InvalidFormatException("Your InputStream was neither an OLE2 stream, nor an OOXML stream"); }
From source file:com.ljh.excel.parser.FromHowTo.java
License:Apache License
public void processFirstSheet(String filename) throws Exception { OPCPackage pkg = OPCPackage.open(filename); XSSFReader r = new XSSFReader(pkg); SharedStringsTable sst = r.getSharedStringsTable(); XMLReader parser = fetchSheetParser(sst); // To look up the Sheet Name / Sheet Order / rID, // you need to process the core Workbook stream. // Normally it's of the form rId# or rSheet# InputStream sheet2 = r.getSheet("rId2"); InputSource sheetSource = new InputSource(sheet2); parser.parse(sheetSource);//from ww w. j a v a 2s . c om sheet2.close(); }
From source file:com.ljh.excel.parser.FromHowTo.java
License:Apache License
public static void processAllSheets(String filename) throws Exception { OPCPackage pkg = OPCPackage.open(filename); XSSFReader r = new XSSFReader(pkg); SharedStringsTable sst = r.getSharedStringsTable(); XMLReader parser = fetchSheetParser(sst); Iterator<InputStream> sheets = r.getSheetsData(); while (sheets.hasNext()) { System.out.println("Processing new sheet:\n"); InputStream sheet = sheets.next(); InputSource sheetSource = new InputSource(sheet); parser.parse(sheetSource);/* www . j a va 2 s. c o m*/ sheet.close(); System.out.println(""); } }