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

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

Introduction

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

Prototype

public static OPCPackage open(File file, PackageAccess access) throws InvalidFormatException 

Source Link

Document

Open a package.

Usage

From source file:com.test.excel.XLSX2CSV.java

License:Apache License

public XLSX2CSV(String inputFilePath, String outputFilePath) throws Exception {
    xlsxPackage = OPCPackage.open(inputFilePath, PackageAccess.READ);
    output = new PrintStream(outputFilePath, OUTPUT_CHARSET);
    // minColumns = -1;
}

From source file:com.toolsverse.etl.connector.excel.ExcelXlsxConnector.java

License:Open Source License

public ConnectorResult populate(ExcelConnectorParams params, DataSet dataSet, Driver driver) throws Exception {
    if (dataSet == null || params == null || Utils.isNothing(dataSet.getName())
            || (driver == null && dataSet.getDriver() == null)) {
        ConnectorResult result = new ConnectorResult();
        result.setRetCode(ConnectorResult.VALIDATION_FAILED_CODE);

        if (dataSet == null)
            result.addResult(ConnectorResource.VALIDATION_ERROR_DATA_SET_NULL.getValue());
        if (driver == null && dataSet.getDriver() == null)
            result.addResult(ConnectorResource.VALIDATION_ERROR_DRIVER_NULL.getValue());
        if (params == null)
            result.addResult(ConnectorResource.VALIDATION_ERROR_PARAMS_NULL.getValue());
        if (dataSet != null && Utils.isNothing(dataSet.getName()))
            result.addResult(ConnectorResource.VALIDATION_ERROR_DATA_SET_NO_NAME.getValue());

        return result;

    }/*from   w  ww.  ja va2s .  co m*/

    dataSet.clear();

    driver = driver != null ? driver : dataSet.getDriver();

    if (!params.isSilent())
        Logger.log(Logger.INFO, EtlLogger.class,
                EtlResource.LOADING_DATASET_MSG.getValue() + dataSet.getName() + "...");

    OPCPackage opcPackage = null;

    String sheetName = (!Utils.isNothing(dataSet.getOwnerName()) && !Utils.isNothing(dataSet.getObjectName())
            || Utils.isNothing(params.getSheetName())) ? dataSet.getName() : params.getSheetName();

    try {
        String fileName = null;

        if (params.getInputStream() == null) {
            fileName = SystemConfig.instance()
                    .getPathUsingAppFolders(params.getFileName(
                            dataSet.getOwnerName() != null ? dataSet.getOwnerName() : dataSet.getName(),
                            ".xlsx", true));

            opcPackage = OPCPackage.open(fileName, PackageAccess.READ);
        } else
            opcPackage = OPCPackage.open(params.getInputStream());

        try {
            process(opcPackage, sheetName, params, dataSet, driver);
        } catch (Exception ex) {
            if (!params.isMaxRowsExceededException(ex) && !params.isSheetAlreadyExatractedException(ex))
                throw ex;
        } finally {
            opcPackage.revert();
        }

        ConnectorResult connectorResult = new ConnectorResult();

        connectorResult.addResult(Utils.format(FileConnectorResource.FILE_POPULATED.getValue(),
                new String[] { FilenameUtils.getName(fileName) }));

        return connectorResult;

    } finally {
        if (params.getInputStream() != null && params.isCloseInput())
            params.getInputStream().close();

        if (params.getAfterCallback() != null)
            params.getAfterCallback().onAfter(dataSet, driver);
    }
}

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

License:Apache License

/**
 * ?Excel//  w ww.  j  ava 2 s. c om
 * 
 * @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: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!");
    }/*  w w  w. j a  v  a2  s.  com*/
    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:ec.util.spreadsheet.poi.FastPoiBook.java

License:EUPL

/**
 * Opens a book from a file.//from w w w. j a  v a  2 s .co m
 *
 * @param file
 * @return
 * @throws IOException
 * @throws OpenXML4JException
 */
@Nonnull
public static FastPoiBook create(@Nonnull File file) throws IOException, OpenXML4JException {
    return create(OPCPackage.open(file.getPath(), PackageAccess.READ));
}

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  w  w  .j a  va  2 s.  c  o  m
        public void close() throws IOException {
            pkg.close();
        }
    };
}

From source file:edu.emory.cci.aiw.cvrg.eureka.etl.spreadsheet.XlsxDataProvider.java

License:Open Source License

/**
 * Create the data provider from the given data file.
 *
 * @param inDataFile The Excel workbook file to use as the data store.
 * @throws DataProviderException Thrown when the workbook can not be
 * accessed, or parsed correctly./*from  ww  w . j av a2s .  c  o  m*/
 */
public XlsxDataProvider(File inDataFile, Locale locale) throws DataProviderException {
    if (inDataFile == null) {
        throw new IllegalArgumentException("inDataFile cannot be null");
    }

    this.logErrorMessage = new MessageFormat(MessageFormat.format("Spreadsheet {0} is missing required sheet",
            new Object[] { inDataFile.getAbsolutePath() }) + " {0}");
    this.exceptionErrorMessage = new MessageFormat("Required worksheet {0} is missing");

    try {
        LOGGER.debug("Creating workbook from {}", inDataFile.getAbsolutePath());
        this.opcPackage = OPCPackage.open(inDataFile.getAbsolutePath(), PackageAccess.READ);
        this.workbook = new XSSFWorkbook(this.opcPackage);
        this.validateWorksheets();
    } catch (InvalidFormatException | InvalidOperationException ex) {
        throw new DataProviderException("Invalid XLSX file", ex);
    } catch (IOException ioe) {
        throw new DataProviderException("Error reading XLSX file", ioe);
    }
    this.messages = locale != null ? ResourceBundle.getBundle("Messages", locale)
            : ResourceBundle.getBundle("Messages");
    this.dataFile = inDataFile;
}

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.j  av a2  s.co m
        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();
    }
}

From source file:excel.FromHowTo.java

License:Apache License

public void processAllSheets(String filename) throws Exception {
    OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
    try {//from w ww.j  av a2 s.  c om
        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);
            sheet.close();
            System.out.println("");
        }
    } finally {
        pkg.close();
    }
}

From source file:excel.XSSF.XLSX2CSV.java

License:Apache License

public static void main(String[] args) throws Exception {
    long startTime = System.currentTimeMillis(); //?
    //        if (args.length < 1) {
    //            System.err.println("Use:");
    //            System.err.println("  XLSX2CSV <xlsx file> [min columns]");
    //            return;
    //        }/*from ww w  . ja  v  a2  s .  c o  m*/

    String path = "/home/sam/Documents/Excel/Book2.xlsx";

    File xlsxFile = new File(path);
    if (!xlsxFile.exists()) {
        System.err.println("Not found or not a file: " + xlsxFile.getPath());
        return;
    }

    int minColumns = -1;
    if (args.length >= 2)
        minColumns = Integer.parseInt(args[1]);

    // The package open is instantaneous, as it should be.
    OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ);
    XLSX2CSV xlsx2csv = new XLSX2CSV(p, System.out, minColumns);
    xlsx2csv.process();
    long endTime = System.currentTimeMillis(); //??
    System.out.println("?? " + (endTime - startTime) / 1000 + "s");
}