Example usage for org.apache.poi.openxml4j.opc OPCPackage close

List of usage examples for org.apache.poi.openxml4j.opc OPCPackage close

Introduction

In this page you can find the example usage for org.apache.poi.openxml4j.opc OPCPackage close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Close the open, writable package and save its content.

Usage

From source file:com.xipin.est.ucontroller.excel.ExcelImportXLSXUtil.java

License:Apache License

/**
 * ?Excel/*from  w w  w.j a  va2s . c o m*/
 * 
 * @param path
 *            
 * @param sheetName
 *            sheet??
 * @param minColumns
 *            
 * @return
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws OpenXML4JException
 * @throws IOException
 */
public static List<String[]> readerExcel(String path, String sheetName, int minColumns)
        throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
    OPCPackage p = OPCPackage.open(path, PackageAccess.READ);
    ExcelImportXLSXUtil xlsx2csv = new ExcelImportXLSXUtil(p, System.out, sheetName, minColumns);
    List<String[]> list = xlsx2csv.process();
    p.close();
    return list;
}

From source file:com.xipin.est.ucontroller.excel.ExcelImportXLSXUtil.java

License:Apache License

public static List<String[]> readerExcel(InputStream i, String sheetName, int minColumns)
        throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
    OPCPackage p = OPCPackage.open(i);
    ExcelImportXLSXUtil xlsx2csv = new ExcelImportXLSXUtil(p, System.out, sheetName, minColumns);
    List<String[]> list = xlsx2csv.process();
    p.close();
    return list;//from  w  w  w. j  av a  2s.com
}

From source file:de.jlo.talendcomp.excel.SpreadsheetFile.java

License:Apache License

private static void encryptFile(String inFilePath, String outFilePath, String password) throws Exception {
    if (password == null || password.trim().isEmpty()) {
        throw new Exception("Password cannot be null or empty!");
    }//from ww w.  j  a va  2s  . c  om
    if (inFilePath == null || inFilePath.trim().isEmpty()) {
        throw new Exception("Input file cannot be null or empty!");
    }
    File inFile = new File(inFilePath);
    if (outFilePath == null || outFilePath.trim().isEmpty()) {
        throw new Exception("Output file cannot be null or empty!");
    }
    File outFile = new File(outFilePath);
    if (inFile.exists() == false) {
        throw new Exception("Excel file to encrypt: " + inFile.getAbsolutePath() + " does not exists!");
    }
    ensureDirExists(outFile);
    POIFSFileSystem fs = new POIFSFileSystem();
    EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
    Encryptor enc = info.getEncryptor();
    enc.confirmPassword(password);
    OPCPackage opc = OPCPackage.open(inFile, PackageAccess.READ_WRITE);
    OutputStream os = enc.getDataStream(fs);
    opc.save(os);
    opc.close();
    FileOutputStream fos = null;
    Exception ex = null;
    try {
        fos = new FileOutputStream(outFile);
        fs.writeFilesystem(fos);
    } catch (Exception e) {
        ex = e;
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e1) {
                // ignore
            }
        }
    }
    if (ex != null) {
        throw ex;
    }
}

From source file:de.ks.idnadrev.expimp.xls.XlsxImporter.java

License:Apache License

public XlsxImportResultCollector importFromFile(File file) {
    resultCollector = new XlsxImportResultCollector();
    checkFile(file);//from  w w  w .ja v  a  2s  .  c  om
    OPCPackage pkg = openPackage(file);
    try {
        XSSFReader reader = new XSSFReader(pkg);
        SharedStringsTable sharedStringsTable = reader.getSharedStringsTable();//used by ms office to store all string values
        log.info("Importing from {}", file);

        Map<Integer, Collection<SingleSheetImport>> importStages = new HashMap<>();

        XSSFReader.SheetIterator iterator = (XSSFReader.SheetIterator) reader.getSheetsData();
        while (iterator.hasNext()) {
            InputStream sheetStream = iterator.next();

            String sheetName = iterator.getSheetName();
            final XlsxImportSheetResult result = resultCollector.getSheetResult(sheetName);

            Class<?> class2Import;
            try {
                class2Import = getClass().getClassLoader().loadClass(sheetName);
            } catch (ClassNotFoundException e) {
                log.info("Could not load class to import {} will skip sheet.", sheetName);
                result.generalError("Could not load class to import " + sheetName + " will skip sheet.", e);
                continue;
            }

            if (class2Import != null) {
                if (importCfg.getIgnored().contains(class2Import)) {
                    continue;
                }
                int stage = dependencyGraph.getStage(class2Import);
                importStages.putIfAbsent(stage, new LinkedList<>());
                SingleSheetImport singleSheetImport = new SingleSheetImport(class2Import, sheetStream,
                        dependencyGraph, reader, result, importCfg);
                importStages.get(stage).add(singleSheetImport);
            }
        }

        importStages.entrySet().forEach(stage -> {
            try {
                executorService.invokeAll(stage.getValue());

                List<List<Future<?>>> collect = stage.getValue().stream()//
                        .map(sheet -> sheet.getRunAfterImport().stream()
                                .map((Runnable r) -> executorService.submit(r))
                                .collect(Collectors.<Future<?>>toList()))//
                        .collect(Collectors.<List<Future<?>>>toList());

                for (List<Future<?>> futureList : collect) {
                    futureList.forEach(future -> {
                        try {
                            future.get();
                        } catch (ExecutionException e) {
                            if (throwOnError) {
                                log.error("Could not run after sheet ", e);
                                throw new RuntimeException(e);
                            }
                        } catch (InterruptedException e) {
                            //
                        }
                    });
                }
            } catch (InterruptedException e1) {
                //
            }
        });

    } catch (OpenXML4JException | IOException e) {
        resultCollector.generalError("Could not read " + file, e);
        if (throwOnError) {
            log.error("Could not read {}", file, e);
            throw new RuntimeException(e);
        }
    } finally {
        try {
            pkg.close();
        } catch (IOException e) {
            resultCollector.generalError("Could not close package " + pkg, e);
            if (throwOnError) {
                log.error("Could not close package {}", pkg, e);
            }
        }
    }
    return resultCollector;
}

From source file:ec.util.spreadsheet.poi.PoiBook.java

License:EUPL

public static PoiBook create(File file) throws IOException, InvalidFormatException {
    final OPCPackage pkg = OPCPackage.open(file.getPath(), PackageAccess.READ);
    return new PoiBook(new XSSFWorkbook(pkg)) {
        @Override//from   w  ww .jav  a2 s .  c om
        public void close() throws IOException {
            pkg.close();
        }
    };
}

From source file:ec.util.spreadsheet.poi.PoiBook.java

License:EUPL

public static PoiBook create(InputStream stream) throws IOException, InvalidFormatException {
    final OPCPackage pkg = OPCPackage.open(stream);
    return new PoiBook(new XSSFWorkbook(pkg)) {
        @Override//from www  .jav  a 2s . c om
        public void close() throws IOException {
            pkg.close();
        }
    };
}

From source file:edu.ur.ir.index.DefaultExcelXmlTextExtractor.java

License:Apache License

/**
 * Extract text from a word 97-2003 document.
 * @throws Exception //from ww  w . j  ava  2 s  . c  om
 * 
 * @see edu.ur.ir.index.FileTextExtractor#getText(java.io.File)
 */
public String getText(File f) throws Exception {
    String text = null;
    if (isFileTooLarge(f) || f.length() <= 0l) {
        return text;
    }

    OPCPackage p = null;
    try {

        p = XSSFWorkbook.openPackage(f.getAbsolutePath());
        XSSFWorkbook workbook = new XSSFWorkbook(p);
        XSSFExcelExtractor extractor = new XSSFExcelExtractor(workbook);

        String myText = extractor.getText();
        if (myText != null && !myText.trim().equals("")) {
            text = myText;
        }
    } catch (OutOfMemoryError oome) {
        text = null;
        log.error("could not extract text", oome);
        throw (oome);
    } catch (Exception e) {
        text = null;
        log.error("could not get text for word document " + f.getAbsolutePath());
        throw (e);
    } finally {
        if (p != null) {
            try {
                p.close();
                p = null;
            } catch (IOException e) {
                log.debug(e);
                p = null;
            }
        }
    }
    return text;
}

From source file:edu.ur.ir.index.DefaultPowerPointXmlTextExtractor.java

License:Apache License

/**
 * Extract text from a word 97-2003 document.
 * @throws Exception /*from w  w w  . j  a v  a 2s  . c  o  m*/
 * 
 * @see edu.ur.ir.index.FileTextExtractor#getText(java.io.File)
 */
public String getText(File f) throws Exception {
    String text = null;
    if (isFileTooLarge(f) || f.length() <= 0l) {
        return text;
    }

    OPCPackage p = null;
    try {
        p = XSLFSlideShow.openPackage(f.getAbsolutePath());
        XSLFSlideShow slideShow = new XSLFSlideShow(p);
        XSLFPowerPointExtractor extractor = new XSLFPowerPointExtractor(slideShow);

        String myText = extractor.getText();
        if (myText != null && !myText.trim().equals("")) {
            text = myText;
        }

    } catch (OutOfMemoryError oome) {
        text = null;
        log.error("could not extract text", oome);
        throw (oome);
    } catch (Exception e) {
        text = null;
        log.error("could not get text for word document " + f.getAbsolutePath(), e);
        throw (e);
    }

    finally {
        if (p != null) {
            try {
                p.close();
                p = null;
            } catch (IOException e) {
                log.debug(e);
                p = null;
            }
        }
    }
    return text;
}

From source file:edu.ur.ir.index.DefaultWordXmlTextExtractor.java

License:Apache License

/**
 * Extract text from a word 97-2003 document.
 * @throws Exception // w  ww. j  a v a2  s  .  co  m
 * 
 * @see edu.ur.ir.index.FileTextExtractor#getText(java.io.File)
 */
public String getText(File f) throws Exception {
    log.debug("Getting text for file " + f.getAbsolutePath());
    String text = null;
    if (isFileTooLarge(f) || f.length() <= 0l) {
        return text;
    }

    OPCPackage p = null;
    try {
        p = XWPFDocument.openPackage(f.getAbsolutePath());
        XWPFDocument wordDocument = new XWPFDocument(p);
        XWPFWordExtractor wordExtractor = new XWPFWordExtractor(wordDocument);

        String myText = wordExtractor.getText();
        if (myText != null && !myText.trim().equals("")) {
            text = myText;
        }

    } catch (OutOfMemoryError oome) {
        text = null;
        log.error("could not extract text", oome);
        throw (oome);
    } catch (Exception e) {
        text = null;
        log.error("could not get text for word document " + f.getAbsolutePath(), e);
        throw (e);
    }

    finally {
        if (p != null) {
            try {
                p.close();
                p = null;
            } catch (IOException e) {
                log.debug(e);
                p = null;
            }
        }
    }
    return text;
}

From source file:excel.FromHowTo.java

License:Apache License

public void processFirstSheet(String filename) throws Exception {
    OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
    try {//from w  w w  .  ja v  a 2  s  .  c om
        XSSFReader r = new XSSFReader(pkg);
        SharedStringsTable sst = r.getSharedStringsTable();
        XMLReader parser = fetchSheetParser(sst);
        // process the first sheet
        InputStream sheet2 = r.getSheetsData().next();
        InputSource sheetSource = new InputSource(sheet2);
        parser.parse(sheetSource);
        sheet2.close();
    } finally {
        pkg.close();
    }
}