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(InputStream in) throws InvalidFormatException, IOException 

Source Link

Document

Open a package.

Usage

From source file:org.eclipse.birt.report.data.oda.excel.impl.util.XlsxFileReader.java

License:Open Source License

public XlsxFileReader(InputStream fis) throws IOException, OpenXML4JException {
    OPCPackage pkg = OPCPackage.open(fis);
    reader = new XSSFReader(pkg);
}

From source file:org.exoplatform.services.document.impl.MSXPPTDocumentReader.java

License:Open Source License

/**
 * Returns only a text from .pptx file content.
 * //from  w  w w  .  java2  s  . c o  m
 * @param is an input stream with .pptx file content.
 * @return The string only with text from file content.
 */
public String getContentAsText(final InputStream is) throws IOException, DocumentReadException {
    if (is == null) {
        throw new IllegalArgumentException("InputStream is null.");
    }
    try {
        if (is.available() == 0) {
            return "";
        }

        final XSLFPowerPointExtractor ppe;
        try {
            ppe = SecurityHelper
                    .doPrivilegedExceptionAction(new PrivilegedExceptionAction<XSLFPowerPointExtractor>() {
                        public XSLFPowerPointExtractor run() throws Exception {
                            return new XSLFPowerPointExtractor(OPCPackage.open(is));
                        }
                    });
        } catch (PrivilegedActionException pae) {
            Throwable cause = pae.getCause();
            if (cause instanceof IOException) {
                throw new DocumentReadException("Can't open presentation.", cause);
            } else if (cause instanceof OpenXML4JRuntimeException) {
                throw new DocumentReadException("Can't open presentation.", cause);
            } else if (cause instanceof OpenXML4JException) {
                throw new DocumentReadException("Can't open presentation.", cause);
            } else if (cause instanceof XmlException) {
                throw new DocumentReadException("Can't open presentation.", cause);
            } else if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            } else {
                throw new RuntimeException(cause);
            }
        }
        return SecurityHelper.doPrivilegedAction(new PrivilegedAction<String>() {
            public String run() {
                return ppe.getText(true, true);
            }
        });
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("An exception occurred: " + e.getMessage());
                }
            }
        }
    }
}

From source file:org.exoplatform.services.document.impl.MSXPPTDocumentReader.java

License:Open Source License

public Properties getProperties(final InputStream is) throws IOException, DocumentReadException {
    final POIPropertiesReader reader = new POIPropertiesReader();
    try {//from   w w w  .ja  v  a 2  s .  com
        SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction<Void>() {
            public Void run() throws Exception {
                reader.readDCProperties(new XSLFSlideShow(OPCPackage.open(is)));
                return null;
            }
        });
    } catch (PrivilegedActionException pae) {
        Throwable cause = pae.getCause();
        if (cause instanceof InvalidFormatException) {
            throw new DocumentReadException("Can't read properties from OOXML document", cause);
        } else if (cause instanceof OpenXML4JException) {
            throw new DocumentReadException("Can't read properties from OOXML document", cause);
        } else if (cause instanceof XmlException) {
            throw new DocumentReadException("Can't read properties from OOXML document", cause);
        } else if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        } else {
            throw new RuntimeException(cause);
        }
    }
    return reader.getProperties();
}

From source file:org.generationcp.middleware.util.PoiEventUserModel.java

License:Open Source License

public void areSheetRowsOverMaxLimit(String filename, int sheetIndex, int maxLimit) throws Exception {

    this.maxLimit = maxLimit;

    OPCPackage pkg = OPCPackage.open(filename);
    XSSFReader r = new XSSFReader(pkg);

    XMLReader parser = this.fetchSheetParser();

    InputStream sheet2 = null;//from w w w .  java  2  s.  c  o m
    // rId2 found by processing the Workbook
    // Seems to either be rId# or rSheet#
    try {
        sheet2 = r.getSheet("rId" + (sheetIndex + 1));
    } catch (Exception e) {
        PoiEventUserModel.LOG.error("Sheet could not be retrieved", e);
    }

    if (sheet2 == null) {
        try {
            sheet2 = r.getSheet("rSheet" + (sheetIndex + 1));
        } catch (Exception e) {
            PoiEventUserModel.LOG.error("Sheet could not be retrieved", e);
        }
    }

    InputSource sheetSource = new InputSource(sheet2);
    parser.parse(sheetSource);
    if (sheet2 != null) {
        sheet2.close();
    }
}

From source file:org.generationcp.middleware.util.PoiEventUserModel.java

License:Open Source License

public void isAnySheetRowsOverMaxLimit(String filename, int maxLimit) throws Exception {

    this.maxLimit = maxLimit;

    OPCPackage pkg = OPCPackage.open(filename);
    XSSFReader r = new XSSFReader(pkg);

    XMLReader parser = this.fetchSheetParser();

    for (int i = 1; i < 10; i++) {

        InputStream sheet = null;
        // rId2 found by processing the Workbook
        // Seems to either be rId# or rSheet#
        try {/*from   w  w w .j  a v  a  2s .  com*/
            sheet = r.getSheet("rId" + i);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (sheet == null) {
            try {
                sheet = r.getSheet("rSheet" + i);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (sheet != null) {
            InputSource sheetSource = new InputSource(sheet);
            parser.parse(sheetSource);
            sheet.close();
        } else {
            break;
        }

    }

}

From source file:org.jberet.support.io.ExcelStreamingItemReader.java

License:Open Source License

@Override
protected void initWorkbookAndSheet(final int startRowNumber) throws Exception {
    InputStream workbookDataInputStream = null;
    XMLStreamReader workbookStreamReader = null;

    try {/*from w  w w . j av  a 2s.  c  om*/
        final OPCPackage opcPackage = OPCPackage.open(inputStream);
        final XSSFReader xssfReader = new XSSFReader(opcPackage);
        workbookDataInputStream = xssfReader.getWorkbookData();
        final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        workbookStreamReader = xmlInputFactory.createXMLStreamReader(workbookDataInputStream);
        sharedStringsTable = xssfReader.getSharedStringsTable();

        /*
        sample sheet element:
        <sheets>
        <sheet name="Movies" sheetId="1" state="visible" r:id="rId2"/>
        <sheet name="Person" sheetId="2" state="visible" r:id="rId3"/>
        </sheets>
         */
        while (workbookStreamReader.hasNext()) {
            if (workbookStreamReader.next() == XMLStreamConstants.START_ELEMENT
                    && "sheet".equals(workbookStreamReader.getLocalName())) {
                final String shn = workbookStreamReader.getAttributeValue(null, "name");
                final String shId = workbookStreamReader.getAttributeValue(null, "sheetId");
                if ((sheetName != null && sheetName.equals(shn))
                        || (sheetName == null && String.valueOf(this.sheetIndex + 1).equals(shId))) {
                    //this is the target sheet
                    final String relationshipId = workbookStreamReader.getAttributeValue(schemaRelationships,
                            "id");
                    sheetInputStream = xssfReader.getSheet(relationshipId);
                    sheetStreamReader = xmlInputFactory.createXMLStreamReader(sheetInputStream);
                    break;
                }
            }
        }
    } finally {
        if (workbookDataInputStream != null) {
            try {
                workbookDataInputStream.close();

            } catch (final Exception e) {
                //ignore
            }
        }
        if (workbookStreamReader != null) {
            try {
                workbookStreamReader.close();
            } catch (final Exception e) {
                //ignore
            }
        }
    }

    /*
    sample row element:
    <row r="1" customFormat="false" ht="15" hidden="false" customHeight="false" outlineLevel="0" collapsed="false">
    <c r="A1" s="0" t="s">
        <v>0</v>
    </c>
    <c r="B1" s="0" t="s">
        <v>1</v>
    </c>
    <c r="C1" s="0" t="s">
        <v>2</v>
    </c>
    <c r="D1" s="0" t="s">
        <v>3</v>
    </c>
    </row>
            
    For inlineStr:
    <c r="A1" t="inlineStr">
    <is>
        <t>Date</t>
    </is>
    </c>
            
    Note: a blank cell does not show up in xml at all. So for list type beanType, need to detect blank cell and add
    null; for map or custom beanType, need to link to the correct header column by r attribute.
     */
    if (header == null) {
        headerMapping = new HashMap<String, String>();
        outerLoop: while (sheetStreamReader.hasNext()) {
            if (sheetStreamReader.next() == XMLStreamConstants.START_ELEMENT
                    && "row".equals(sheetStreamReader.getLocalName())) {
                final int rowNum = Integer.parseInt(sheetStreamReader.getAttributeValue(null, "r"));

                if (headerRow + 1 == rowNum) {
                    // got the header row, next loop through header row cells
                    final List<String> headerVals = new ArrayList<String>();
                    while (sheetStreamReader.hasNext()) {
                        final int event = sheetStreamReader.next();
                        if (event == XMLStreamConstants.START_ELEMENT
                                && "c".equals(sheetStreamReader.getLocalName())) {
                            final String label = getColumnLabel(sheetStreamReader.getAttributeValue(null, "r"));
                            final String value = getCellStringValue();
                            headerVals.add(value);
                            headerMapping.put(label, value);
                        } else if (event == XMLStreamConstants.END_ELEMENT
                                && "row".equals(sheetStreamReader.getLocalName())) {
                            header = headerVals.toArray(new String[headerVals.size()]);
                            currentRowNum = rowNum - 1;
                            break outerLoop;
                        }
                    }
                }
            }
        }
    }

    //fast forward to the start row, which may not immediately follow header row
    while (currentRowNum < startRowNumber - 1 && sheetStreamReader.hasNext()) {
        if (sheetStreamReader.next() == XMLStreamConstants.START_ELEMENT
                && "row".equals(sheetStreamReader.getLocalName())) {
            currentRowNum = Integer.parseInt(sheetStreamReader.getAttributeValue(null, "r")) - 1;
        } else if (sheetStreamReader.next() == XMLStreamConstants.END_ELEMENT
                && "row".equals(sheetStreamReader.getLocalName())) {
            if (currentRowNum >= startRowNumber - 1) {
                break;
            }
        }
    }
}

From source file:org.jeecgframework.poi.excel.imports.ExcelImportServer.java

License:Apache License

/**
 * Excel  field  Integer,Long,Double,Date,String,Boolean
 * /*from   w  w w  .  j a v a  2 s .c  o m*/
 * @param inputstream
 * @param pojoClass
 * @param params
 * @return
 * @throws Exception
 */
public ExcelImportResult importExcelByIs(InputStream inputstream, Class<?> pojoClass, ImportParams params)
        throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Excel import start ,class is {}", pojoClass);
    }
    List<T> result = new ArrayList<T>();
    Workbook book = null;
    boolean isXSSFWorkbook = true;
    if (!(inputstream.markSupported())) {
        inputstream = new PushbackInputStream(inputstream, 8);
    }
    if (POIFSFileSystem.hasPOIFSHeader(inputstream)) {
        book = new HSSFWorkbook(inputstream);
        isXSSFWorkbook = false;
    } else if (POIXMLDocument.hasOOXMLHeader(inputstream)) {
        book = new XSSFWorkbook(OPCPackage.open(inputstream));
    }
    createErrorCellStyle(book);
    Map<String, PictureData> pictures;
    for (int i = 0; i < params.getSheetNum(); i++) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(" start to read excel by is ,startTime is {}", new Date().getTime());
        }
        if (isXSSFWorkbook) {
            pictures = PoiPublicUtil.getSheetPictrues07((XSSFSheet) book.getSheetAt(i), (XSSFWorkbook) book);
        } else {
            pictures = PoiPublicUtil.getSheetPictrues03((HSSFSheet) book.getSheetAt(i), (HSSFWorkbook) book);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(" end to read excel by is ,endTime is {}", new Date().getTime());
        }
        result.addAll(importExcel(result, book.getSheetAt(i), pojoClass, params, pictures));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(" end to read excel list by pos ,endTime is {}", new Date().getTime());
        }
    }
    if (params.isNeedSave()) {
        saveThisExcel(params, pojoClass, isXSSFWorkbook, book);
    }
    return new ExcelImportResult(result, verfiyFail, book);
}

From source file:org.jreserve.gui.poi.read.xlsx.XlsxReader.java

License:Open Source License

@Override
public T read(File file) throws IOException {
    try {//from   w w  w  .  j  a  v a 2 s  . c  o  m
        pkg = OPCPackage.open(file);
        XSSFReader reader = new XSSFReader(pkg);
        readReader(reader);
        return getResult();
    } catch (Exception ex) {
        String path = file == null ? null : file.getAbsolutePath();
        String msg = String.format("Unabel to read file '%s'!", path);
        logger.log(Level.SEVERE, msg, ex);
        throw new IOException(msg, ex);
    } finally {
        close();
    }
}

From source file:org.nekorp.workflow.desktop.control.imp.ProgramacionServicioWizardImp.java

License:Apache License

@Override
public void importarArchivo(File archivo) {
    programacionMetadata.setDetalles("");
    OPCPackage pkg = null;/*w ww  .  j a va 2  s  .c om*/
    try {
        addDetail("Leyendo archivo: " + archivo.getCanonicalPath());
        pkg = OPCPackage.open(archivo);
        XSSFWorkbook wb = new XSSFWorkbook(pkg);
        //Workbook wb = WorkbookFactory.create(archivo);
        Sheet sheet = wb.getSheetAt(0);
        //Row encabezado = sheet.getRow(0);
        List<String> nombresServicios = null;
        boolean inicio = true;
        nuevosAutos = new LinkedList<>();
        nuevosServicio = new LinkedList<>();
        for (Row row : sheet) {
            if (inicio) {
                nombresServicios = procesarEncabezado(row);
                inicio = false;
            } else {
                if (row.getPhysicalNumberOfCells() == nombresServicios.size()) {
                    Auto autoCargado = new Auto();
                    cargarDatosAuto(row, autoCargado);
                    autoBridge.load(autoCargado, servicio.getAuto());
                    Servicio nuevoServicio = new Servicio();
                    if (buscarNuevoServicio(row, nuevoServicio, nombresServicios, rangoNuevo)) {
                        //se intentan cargar
                        servicioBridge.load(nuevoServicio, servicio);
                        addDetail("Se encontro un nuevo servicio para el auto con numero de serie: "
                                + autoCargado.getNumeroSerie());
                        addDetail("Descripcin del servicio encontrado:\n" + nuevoServicio.getDescripcion());
                        if (validacionGeneralDatosAuto.isValido()) {
                            nuevosAutos.add(autoCargado);
                            nuevosServicio.add(nuevoServicio);
                        } else {
                            addDetail(
                                    "los datos del nuevo servicio tienen los siguientes errores y no se dara de alta:");
                            addDetail(validacionDatosAuto.concatenaErrores());
                        }
                    }
                    List<AlertaServicio> nuevasAlertas = buscarAlertas(row, nombresServicios, rangoAlerta);
                    for (AlertaServicio x : nuevasAlertas) {
                        x.setMarcaAuto(autoCargado.getMarca());
                        x.setPlacasAuto(autoCargado.getPlacas());
                        x.setTipoAuto(autoCargado.getTipo());
                        x.setNombreCliente(servicio.getCliente().getNombre());
                        addDetail("Se encontro un servicio proximo para el auto con numero de serie: "
                                + autoCargado.getNumeroSerie());
                        addDetail("Descripcin de la nueva alerta:\n" + x.getDescripcionServicio());
                        alertas.add(x);
                    }
                    AlertaVerificacion nuevaAlerta = buscarAlertasVerificacion(autoCargado.getPlacas());
                    if (nuevaAlerta != null) {
                        addDetail("Se encontro un auto que pudiera necesitar verificacin: "
                                + autoCargado.getNumeroSerie());
                        addDetail(
                                "placas: " + nuevaAlerta.getPlacas() + " periodo: " + nuevaAlerta.getPeriodo());
                        alertasVerificacion.add(nuevaAlerta);
                    }
                }
            }
        }
        if (nuevosServicio.size() > 0) {
            if (nuevosServicio.size() == 1) {
                addDetail("Se tiene listo para crear un nuevo servicio");
            } else {
                addDetail("Se tienen listos para crear " + nuevosServicio.size() + " servicios nuevos");
            }
        } else {
            addDetail("No se encontro ningun nuevo servicio");
        }
        int cantidadAlertas = alertas.size() + alertasVerificacion.size();
        if (cantidadAlertas > 0) {
            if (cantidadAlertas == 1) {
                addDetail("Se tiene lista para enviar una nueva alerta");
            } else {
                addDetail("Se tienen listas para enviar " + cantidadAlertas + " alertas");
            }
        } else {
            addDetail("No se encontro ninguna alerta");
        }
        if (nuevosServicio.size() > 0 || cantidadAlertas > 0) {
            validacionGeneralProgramacion.setValido(true);
        } else {
            validacionGeneralProgramacion.setValido(false);
        }
    } catch (IOException | InvalidFormatException | IllegalArgumentException ex) {
        ProgramacionServicioWizardImp.LOGGER.error("exploto!!!", ex);
        addDetail("ocurrio un error inesperado al leer el archivo." + ex.getMessage());
    } finally {
        if (pkg != null) {
            try {
                pkg.close();
            } catch (IOException ex) {
                //ProgramacionServicioWizardImp.LOGGER.error("exploto!!!", ex);
            }
        }
    }
}

From source file:org.nuxeo.ecm.core.convert.plugins.text.extractors.XLX2TextConverter.java

License:Apache License

@Override
public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters)
        throws ConversionException {

    InputStream stream = null;//from ww  w  .j a v  a 2 s .c o  m
    StringBuffer sb = new StringBuffer();

    try {
        Blob blob = blobHolder.getBlob();

        if (blob.getLength() > maxSize4POI) {
            return runFallBackConverter(blobHolder, "xl/");
        }

        stream = blob.getStream();

        OPCPackage p = OPCPackage.open(stream);
        XSSFWorkbook workbook = new XSSFWorkbook(p);
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            XSSFSheet sheet = workbook.getSheetAt(i);
            Iterator<Row> rows = sheet.rowIterator();
            while (rows.hasNext()) {
                XSSFRow row = (XSSFRow) rows.next();
                Iterator<Cell> cells = row.cellIterator();
                while (cells.hasNext()) {
                    XSSFCell cell = (XSSFCell) cells.next();
                    appendTextFromCell(cell, sb);
                }
                sb.append(ROW_SEP);
            }
        }
        return new SimpleCachableBlobHolder(Blobs.createBlob(sb.toString()));
    } catch (IOException | OpenXML4JException e) {
        throw new ConversionException("Error during XLX2Text conversion", e);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                log.error("Error while closing Blob stream", e);
            }
        }
    }
}