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:lp.XLSXhandler.java

public Object[] opener(File uploaded, String name) {

    double[][] data = new double[0][0];
    String[] dmuNames = new String[0];
    String[] variable_names = new String[0];
    Object[] obj = new Object[5];

    try {/*from ww  w.  j a  va2  s .c  o m*/

        OPCPackage pkg = OPCPackage.open(uploaded);
        XSSFWorkbook wb = new XSSFWorkbook(pkg);
        XSSFSheet sheet1 = wb.getSheetAt(0);

        //I find the number of the rows in the file! (0-based)
        int rows = sheet1.getLastRowNum();
        System.out.println("Total Rows of DATA in the file: " + rows);

        //I find the number of columns! (1-based)
        int columns = sheet1.getRow(0).getLastCellNum();
        System.out.println("Total Columns of DATA in the file: " + columns);

        data = new double[rows][columns - 1];
        dmuNames = new String[rows];
        variable_names = new String[columns];

        Row row_trav;
        Cell cell_trav;

        // Retrieve data from file to array
        for (int i = 0; i <= rows; i++) {
            row_trav = sheet1.getRow(i);

            for (int k = 0; k < columns; k++) {
                cell_trav = row_trav.getCell(k);

                if (i == 0) {
                    //we are at line 0 of the uploaded file
                    variable_names[k] = cell_trav.getStringCellValue();
                }

                if (k == 0 && i < rows) {
                    //we are at column 0 of the uploaded file

                    Row row_name = sheet1.getRow(i + 1);
                    cell_trav = row_name.getCell(0);
                    dmuNames[i] = cell_trav.getStringCellValue();
                }
                if (i > 0 && k > 0) {
                    data[i - 1][k - 1] = cell_trav.getNumericCellValue();
                }
            }
        }

        obj[0] = data;
        obj[1] = rows;
        obj[2] = columns;
        obj[3] = variable_names;
        obj[4] = dmuNames;

    } catch (InvalidFormatException e) {
    } catch (IOException e) {
    }

    return obj;
}

From source file:lp.XLSXhandler.java

public boolean fileformat(File uploaded) {

    boolean f = true;
    try {/* www  . j  a v  a  2  s.  c  om*/
        OPCPackage pkg = OPCPackage.open(uploaded);
        XSSFWorkbook wb = new XSSFWorkbook(pkg);
        XSSFSheet sheet1 = wb.getSheetAt(0);

        //I find the number of the rows in the file! (0-based)
        int rows = sheet1.getLastRowNum() + 1;

        //I find the number of columns! (1-based)
        int columns = sheet1.getRow(0).getLastCellNum();

        /*
         *  I will check only the data part! not the names of the DMUs
         */
        Row row_check;
        Cell cell_check;

        for (int i = 1; i < rows; i++) {
            row_check = sheet1.getRow(i);
            for (int k = 1; k < columns; k++) {
                cell_check = row_check.getCell(k);

                /*If there is something else exept a number (0)
                 * or excel function (2)
                 */
                int current = cell_check.getCellType();
                if (current == 0 || current == 2) {

                } else {
                    f = false;
                }
            }
        }

    } catch (InvalidFormatException e) {
        e.getMessage();
        new Lp_first().cleanDir();

    } catch (IOException e) {
    }

    return f;
}

From source file:net.geoprism.data.etl.excel.ExcelSheetReader.java

License:Open Source License

public void process(InputStream stream) throws Exception {
    try {/*from   ww w .j av a 2 s.com*/
        OPCPackage pkg = OPCPackage.open(stream);

        ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg);
        XSSFReader xssfReader = new XSSFReader(pkg);
        StylesTable styles = xssfReader.getStylesTable();
        XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();

        while (iter.hasNext()) {
            InputStream sheet = iter.next();

            try {
                String sheetName = iter.getSheetName();

                this.handler.startSheet(sheetName);

                InputSource sheetSource = new InputSource(sheet);
                ContentHandler handler = new XSSFSheetXMLHandler(styles, strings, this.handler, this.formatter,
                        false);

                XMLReader reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
                reader.setContentHandler(handler);
                reader.parse(sheetSource);

                this.handler.endSheet();
            } finally {
                sheet.close();
            }
        }
    } finally {
        stream.close();
    }
}

From source file:net.java.amateras.xlsbeans.xssfconverter.WorkbookFinder.java

License:Apache License

/**
 * return workbook wrapper.//from  www.j  ava 2s  .com
 *
 * @param is Excel InputStream
 * @param type TYPE_JXL:JExcel API Wrapper / TYPE_HSSF:hssf Wrapper / TYPE_XSSF:xssf Wrapper
 * @return Workbook
 */
public static WWorkbook find(InputStream is, String type) throws Exception {
    WWorkbook retbook = null;
    if (TYPE_JXL.equals(type)) {
        WorkbookSettings settings = new WorkbookSettings();
        settings.setGCDisabled(true);
        settings.setEncoding("ISO8859_1");
        Workbook w = Workbook.getWorkbook(is, settings);
        retbook = new JxlWWorkbookImpl(w);
    } else if (TYPE_HSSF.equals(type)) {
        org.apache.poi.ss.usermodel.Workbook ssWorkbook = new HSSFWorkbook(is);
        retbook = new XssfWWorkbookImpl(ssWorkbook);
    } else if (TYPE_XSSF.equals(type)) {
        org.apache.poi.ss.usermodel.Workbook ssWorkbook = new XSSFWorkbook(OPCPackage.open(is));
        retbook = new XssfWWorkbookImpl(ssWorkbook);
    } else {
        throw new IllegalArgumentException("type must be defined by TYPE_JXL or TYPE_HSSF or TYPE_XSSF");
    }
    return retbook;
}

From source file:net.ontopia.topicmaps.classify.OOXMLPowerpointFormatModule.java

License:Apache License

public void readContent(ClassifiableContentIF cc, TextHandlerIF handler) {
    try {//from  w w  w  . ja  v  a  2s . c om
        OPCPackage opc = OPCPackage.open(new ByteArrayInputStream(cc.getContent()));
        XSLFPowerPointExtractor extractor = new XSLFPowerPointExtractor(opc);
        String s = extractor.getText();
        char[] c = s.toCharArray();
        handler.startRegion("document");
        handler.text(c, 0, c.length);
        handler.endRegion();
    } catch (Exception e) {
        throw new OntopiaRuntimeException(e);
    }
}

From source file:net.ontopia.topicmaps.classify.OOXMLWordFormatModule.java

License:Apache License

public void readContent(ClassifiableContentIF cc, TextHandlerIF handler) {
    try {/*from ww w. ja va 2s  . c  o m*/
        OPCPackage opc = OPCPackage.open(new ByteArrayInputStream(cc.getContent()));
        XWPFWordExtractor extractor = new XWPFWordExtractor(opc);
        String s = extractor.getText();
        char[] c = s.toCharArray();
        handler.startRegion("document");
        handler.text(c, 0, c.length);
        handler.endRegion();
    } catch (Exception e) {
        throw new OntopiaRuntimeException(e);
    }
}

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

License:Apache License

/**
 * {@inheritDoc}/*  w  ww.  ja va 2  s .c o  m*/
 */
@Override
public void parse(InputStream inputStream, long filesize, ContentParserOptions options,
        MutableGenericContext context) throws Exception {

    OPCPackage opcPackage = OPCPackage.open(inputStream);
    POIXMLTextExtractor extractor = createExtractor(opcPackage);
    CoreProperties coreProperties = extractor.getCoreProperties();
    String title = coreProperties.getTitle();
    if (title != null) {
        context.setVariable(VARIABLE_NAME_TITLE, title);
    }
    String author = coreProperties.getCreator();
    if (author != null) {
        context.setVariable(VARIABLE_NAME_CREATOR, author);
    }
    String keywords = coreProperties.getKeywords();
    if (keywords != null) {
        context.setVariable(VARIABLE_NAME_KEYWORDS, keywords);
    }
    context.setVariable(VARIABLE_NAME_TEXT, extractText(extractor, filesize));
}

From source file:net.sourceforge.docfetcher.model.parse.TestParseFromZip.java

License:Open Source License

@Test
public void testZippedOffice2007() throws Exception {
    new ZipAndRun(TestFiles.docx) {
        protected void handleInputStream(InputStream in) throws Exception {
            int length = ExtractorFactory.createExtractor(in).getText().length();
            assertEquals(659, length);/*w w w .ja  v a 2 s  .  co m*/
        }
    };
    new ZipAndRun(TestFiles.docx) {
        protected void handleInputStream(InputStream in) throws Exception {
            OPCPackage pkg = OPCPackage.open(in);
            pkg.getPackageProperties();
            Closeables.closeQuietly(pkg);
        }
    };
}

From source file:net.sourceforge.docfetcher.model.parse.TestParseFromZip.java

License:Open Source License

@Test(expected = IOException.class)
public void testZippedOffice2007Fail() throws Exception {
    // This will fail because we're trying to read the same InputStream twice
    new ZipAndRun(TestFiles.docx) {
        protected void handleInputStream(InputStream in) throws Exception {
            int length = ExtractorFactory.createExtractor(in).getText().length();
            assertEquals(659, length);/*from www .j  av  a  2  s.  c o m*/
            OPCPackage pkg = OPCPackage.open(in);
            pkg.getPackageProperties();
            Closeables.closeQuietly(pkg);
        }
    };
}

From source file:openslide.module.webserver.PPTX2SVG.java

License:Apache License

/**
 * parse file to svg document/*from  w  w w .  ja  v a2 s. c  o  m*/
 * @param file_name -required-  {string} fullpath file
 * @return slide_list
 * @throws Exception
 */
public static ArrayList<String> parse(String file_name) throws Exception {

    String file = file_name;
    ArrayList<String> slide_list = new ArrayList<String>();
    System.out.println("Processing " + file);

    // read the .pptx file
    XMLSlideShow ppt = new XMLSlideShow(OPCPackage.open(file));

    Dimension pgsize = ppt.getPageSize();

    // convert each slide into a .svg file
    XSLFSlide[] slide = ppt.getSlides();
    for (int i = 0; i < slide.length; i++) {
        // Create initial SVG DOM
        DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
        Document doc = domImpl.createDocument("http://www.w3.org/2000/svg", "svg", null);
        //Use Batik SVG Graphics2D driver
        SVGGraphics2D graphics = new SVGGraphics2D(doc);
        graphics.setRenderingHint(XSLFRenderingHint.IMAGE_RENDERER, new WMFImageRender());
        graphics.setSVGCanvasSize(pgsize);

        String title = slide[i].getTitle();
        System.out.println("Rendering slide " + (i + 1) + (title == null ? "" : ": " + title));

        // draw stuff. All the heavy-lifting happens here
        slide[i].draw(graphics);

        // save the result.
        int sep = file.lastIndexOf(".");
        String fname = file.substring(0, sep == -1 ? file.length() : sep) + "-" + (i + 1) + ".svg";
        slide_list.add(fname);
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fname), "UTF-8");
        DOMSource domSource = new DOMSource(graphics.getRoot());
        StreamResult streamResult = new StreamResult(out);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.transform(domSource, streamResult);
        out.flush();
        out.close();
    }
    System.out.println("Done");

    return slide_list;
}