Example usage for org.apache.poi.hssf.eventusermodel HSSFEventFactory processEvents

List of usage examples for org.apache.poi.hssf.eventusermodel HSSFEventFactory processEvents

Introduction

In this page you can find the example usage for org.apache.poi.hssf.eventusermodel HSSFEventFactory processEvents.

Prototype

public void processEvents(HSSFRequest req, InputStream in) 

Source Link

Document

Processes a DocumentInputStream into essentially Record events.

Usage

From source file:ambit.test.io.POItest.java

License:Open Source License

/**
 * Read an excel file and spit out what we find.
 * /* w  w w.ja  va2 s .com*/
 * @param file
 *            Expect one argument that is the file to read.
 * @throws IOException
 *             When there is an error processing the file.
 */
public void readXLSFile(String file) throws IOException {
    // create a new file input stream with the input file specified
    // at the command line
    FileInputStream fin = new FileInputStream(file);
    // create a new org.apache.poi.poifs.filesystem.Filesystem
    POIFSFileSystem poifs = new POIFSFileSystem(fin);
    // get the Workbook (excel part) stream in a InputStream
    InputStream din = poifs.createDocumentInputStream("Workbook");
    // construct out HSSFRequest object
    HSSFRequest req = new HSSFRequest();
    // lazy listen for ALL records with the listener shown above
    req.addListenerForAllRecords(new POIExample());
    // create our event factory
    HSSFEventFactory factory = new HSSFEventFactory();
    // process our events based on the document input stream
    factory.processEvents(req, din);
    // once all the events are processed close our file input stream
    fin.close();
    // and our document input stream (don't want to leak these!)
    din.close();
    System.out.println("done.");
}

From source file:ambit2.core.test.io.POItest.java

License:Open Source License

/**
 * Read an excel file and spit out what we find.
 * //from w  w w  .jav  a  2s  . c  o  m
 * @param file
 *            Expect one argument that is the file to read.
 * @throws IOException
 *             When there is an error processing the file.
 */
public void readXLSFile(String file) throws Exception {

    // create a new file input stream with the input file specified
    // at the command line
    FileInputStream fin = new FileInputStream(getClass().getClassLoader().getResource(file).getFile());
    // create a new org.apache.poi.poifs.filesystem.Filesystem
    POIFSFileSystem poifs = new POIFSFileSystem(fin);
    // get the Workbook (excel part) stream in a InputStream
    InputStream din = poifs.createDocumentInputStream("Workbook");
    // construct out HSSFRequest object
    HSSFRequest req = new HSSFRequest();
    // lazy listen for ALL records with the listener shown above
    req.addListenerForAllRecords(new POIListener());
    // create our event factory
    HSSFEventFactory factory = new HSSFEventFactory();
    // process our events based on the document input stream
    factory.processEvents(req, din);
    // once all the events are processed close our file input stream
    fin.close();
    // and our document input stream (don't want to leak these!)
    din.close();
}

From source file:com.daphne.es.showcase.excel.service.ExcelDataService.java

License:Apache License

/**
 *  excel 2003 biff?/*from   w ww.  ja va2  s  . com*/
 * xml? ?SAX
 * @param user
 * @param is
 */
@Async
public void importExcel2003(final User user, final InputStream is) {

    ExcelDataService proxy = ((ExcelDataService) AopContext.currentProxy());

    BufferedInputStream bis = null;
    InputStream dis = null;
    try {
        long beginTime = System.currentTimeMillis();

        List<ExcelData> dataList = Lists.newArrayList();

        //?
        bis = new BufferedInputStream(is);
        //  org.apache.poi.poifs.filesystem.Filesystem
        POIFSFileSystem poifs = new POIFSFileSystem(bis);
        // ?  Workbook(excel )?
        dis = poifs.createDocumentInputStream("Workbook");
        //  HSSFRequest
        HSSFRequest req = new HSSFRequest();

        // ?
        req.addListenerForAllRecords(new Excel2003ImportListener(proxy, dataList, batchSize));
        //  
        HSSFEventFactory factory = new HSSFEventFactory();
        // ???
        factory.processEvents(req, dis);

        //??batchSize?
        if (dataList.size() > 0) {
            proxy.doBatchSave(dataList);
        }

        long endTime = System.currentTimeMillis();

        Map<String, Object> context = Maps.newHashMap();
        context.put("seconds", (endTime - beginTime) / 1000);
        notificationApi.notify(user.getId(), "excelImportSuccess", context);
    } catch (Exception e) {
        log.error("excel import error", e);
        Map<String, Object> context = Maps.newHashMap();
        context.put("error", e.getMessage());
        notificationApi.notify(user.getId(), "excelImportError", context);
    } finally {
        // ?
        IOUtils.closeQuietly(bis);
        // ?
        IOUtils.closeQuietly(dis);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.ExcelSXSSFRowStream.java

License:Apache License

/**
 * Reads HSSF (XLS) format excel file using Apache POI streaming SXSSF API.
 *
 * @param xlsFile//  w ww  .jav  a 2s . com
 *            excel HSSF format file to read
 *
 * @throws IOException
 *             if excel file or workbook can't be read
 */
protected void readXLS(File xlsFile) throws IOException {
    NPOIFSFileSystem fs = null;
    InputStream dis = null;
    boolean passwordSet = false;

    try {
        fs = new NPOIFSFileSystem(xlsFile, true);
        DirectoryNode root = fs.getRoot();
        if (root.hasEntry("EncryptedPackage")) { // NON-NLS
            dis = DocumentFactoryHelper.getDecryptedStream(fs, wbPass);
        } else {
            if (wbPass != null) {
                Biff8EncryptionKey.setCurrentUserPassword(wbPass);
                passwordSet = true;
            }
            dis = fs.createDocumentInputStream("Workbook"); // NON-NLS
        }
        HSSFRequest req = new HSSFRequest();

        XLSEventListener listener = new XLSEventListener(this);
        FormatTrackingHSSFListener formatsListener = new FormatTrackingHSSFListener(listener,
                Locale.getDefault());
        listener.setFormatListener(formatsListener);
        req.addListenerForAllRecords(formatsListener);
        HSSFEventFactory factory = new HSSFEventFactory();
        factory.processEvents(req, dis);
    } finally {
        if (passwordSet) {
            Biff8EncryptionKey.setCurrentUserPassword((String) null);
        }

        Utils.close(fs);
        Utils.close(dis);
    }
}

From source file:com.sonicle.webtop.core.io.input.XlsBaseProcessor.java

License:Open Source License

public void process() {
    HSSFRequest request = createRequest();
    HSSFEventFactory factory = new HSSFEventFactory();
    try {/*from ww w .  j a  va 2 s  .c om*/
        factory.processEvents(request, is);
    } catch (IllegalStateException ex) {
        // Don't bother about illegal state of stream closed
    }
}

From source file:com.toolsverse.etl.metadata.excel.ExcelFileMetadata.java

License:Open Source License

@Override
public DataSet getTablesByType(InputStream inputSteam, String name, String pattern, String type)
        throws Exception {
    DataSet dataSet = new DataSet();
    dataSet.setName("tables");

    FieldDef fieldDef = new FieldDef();
    fieldDef.setName("File");
    fieldDef.setSqlDataType(Types.VARCHAR);
    dataSet.addField(fieldDef);// w  ww . jav a2 s.  c  o m

    fieldDef = new FieldDef();
    fieldDef.setName("Name");
    fieldDef.setSqlDataType(Types.VARCHAR);
    dataSet.addField(fieldDef);

    dataSet.setKeyFields("Name");

    InputStream din = null;

    try {
        POIFSFileSystem poifs = new POIFSFileSystem(inputSteam);
        din = poifs.createDocumentInputStream("Workbook");
        HSSFRequest req = new HSSFRequest();

        req.addListenerForAllRecords(new SheetReader(name, dataSet));
        HSSFEventFactory factory = new HSSFEventFactory();

        try {
            factory.processEvents(req, din);
        } catch (Exception ex) {
            if (!Utils.isParticularException(ex, SHEETS_EXTRACTED_EXCEPTION))
                throw ex;
        }
    } finally {
        if (din != null)
            din.close();
    }

    return dataSet;
}

From source file:com.toolsverse.etl.metadata.excel.ExcelFileMetadata.java

License:Open Source License

@Override
public DataSet getTablesByType(String catalog, String schema, String pattern, String type) throws Exception {
    DataSet dataSet = new DataSet();
    dataSet.setName(TABLES_DATASET_TYPE);

    FieldDef fieldDef = new FieldDef();
    fieldDef.setName("File");
    fieldDef.setSqlDataType(Types.VARCHAR);
    dataSet.addField(fieldDef);/*from ww  w. j  av a  2s  . com*/

    fieldDef = new FieldDef();
    fieldDef.setName("Name");
    fieldDef.setSqlDataType(Types.VARCHAR);
    dataSet.addField(fieldDef);

    dataSet.setKeyFields("Name");

    FileInputStream fin = null;
    InputStream din = null;

    try {
        fin = new FileInputStream(catalog);
        POIFSFileSystem poifs = new POIFSFileSystem(fin);
        din = poifs.createDocumentInputStream("Workbook");
        HSSFRequest req = new HSSFRequest();

        req.addListenerForAllRecords(new SheetReader(catalog, dataSet));
        HSSFEventFactory factory = new HSSFEventFactory();

        try {
            factory.processEvents(req, din);
        } catch (Exception ex) {
            if (!Utils.isParticularException(ex, SHEETS_EXTRACTED_EXCEPTION))
                throw ex;
        }
    } finally {
        if (fin != null)
            fin.close();
        if (din != null)
            din.close();
    }

    return dataSet;
}

From source file:net.sf.mmm.content.parser.impl.poi.ContentParserXls.java

License:Apache License

/**
 * {@inheritDoc}// w  ww .j  ava 2s  .  c  o m
 */
@Override
protected String extractText(POIFSFileSystem poiFs, long filesize, ContentParserOptions options)
        throws Exception {

    int maxBufferSize = options.getMaximumBufferSize();
    int maxCharSize = maxBufferSize / 2;
    InputStream documentInputStream = poiFs.createDocumentInputStream(POIFS_EXCEL_DOC);
    // actually there seems no smart guess for the initial capacity of
    // textBuffer
    // the text length can have any ration to documentInputStream.available()
    // the only possibility would be to create the string buffer in the listener
    // from the size of the SSTRecord. In this case stable code is better than
    // saving a tiny percent of performance...
    StringBuilder textBuffer = new StringBuilder(1024);
    try {
        HSSFRequest req = new HSSFRequest();
        req.addListenerForAllRecords(new ExcelListener(textBuffer, maxCharSize));
        HSSFEventFactory factory = new HSSFEventFactory();
        factory.processEvents(req, documentInputStream);
    } finally {
        documentInputStream.close();
    }
    return textBuffer.toString();
}

From source file:org.datagator.tools.importer.impl.XlsxInputStreamExtractor.java

License:Apache License

public XlsxInputStreamExtractor(InputStream stream) throws IOException {
    super(stream);
    _queue = new ArrayBlockingQueue<ImmutablePair<AtomType, Object>>(MAX_QUEUE_CAPACITY);
    final HSSFRequest request = new HSSFRequest();
    request.addListenerForAllRecords(new MissingRecordAwareHSSFListener(new EventTransformer(_queue)));
    final HSSFEventFactory factory = new HSSFEventFactory();
    factory.processEvents(request, stream);
}

From source file:org.jab.docsearch.converters.Excel.java

License:Open Source License

/**
 * @see ConverterInterface#parse()/*  ww w.j  ava 2 s. c o  m*/
 */
@Override
public void parse() throws ConverterException {
    if (filename == null) {
        log.error("parse() filename is null");
        throw new ConverterException("Word::parse() filename is null");
    }

    // get meta data
    FileInputStream fin = null;
    try {
        fin = new FileInputStream(filename);

        POIFSReader r = new POIFSReader();
        MyPOIFSReaderListener mpfsrl = new MyPOIFSReaderListener();
        r.registerListener(mpfsrl, "\005SummaryInformation");
        r.read(fin);

        fin.close();

        // get meta data
        documentTitle = mpfsrl.getTitle();
        documentAuthor = mpfsrl.getAuthor();
        documentKeywords = mpfsrl.getKeywords();
    } catch (IOException ioe) {
        log.error("parse() failed at Excel file=" + filename, ioe);
        throw new ConverterException("Excel::parse() failed at Excel file=" + filename, ioe);
    } catch (Exception e) {
        log.error("parse() failed at Excel file=" + filename, e);
        throw new ConverterException("Excel::parse() failed", e);
    } finally {
        IOUtils.closeQuietly(fin);
    }

    if (log.isDebugEnabled()) {
        log.debug("parse() Excel file='" + filename + "'" + Layout.LINE_SEP + "title='" + documentTitle + "'"
                + Layout.LINE_SEP + "author='" + documentAuthor + "'" + Layout.LINE_SEP + "keywords='"
                + documentKeywords + "'");
    }

    // get text
    DocumentInputStream din = null;
    ExcelListener el = new ExcelListener();
    try {
        // proceed to write to file
        // create a new file input stream with the input file specified
        // at the command line
        fin = new FileInputStream(filename);

        POIFSFileSystem poifs = new POIFSFileSystem(fin);
        din = poifs.createDocumentInputStream("Workbook");
        HSSFRequest req = new HSSFRequest();
        req.addListenerForAllRecords(el);
        HSSFEventFactory factory = new HSSFEventFactory();
        factory.processEvents(req, din);

        fin.close();

        // get text
        documentText = el.getText().toString();
    } catch (IOException ioe) {
        log.error("parse() failed at Excel file=" + filename, ioe);
        throw new ConverterException("Excel::parse() failed at Excel file=" + filename, ioe);
    } catch (Exception e) {
        log.error("parse() failed", e);
        throw new ConverterException("Excel::parse() failed", e);
    } finally {
        IOUtils.closeQuietly(din);
        IOUtils.closeQuietly(fin);
    }
}