Java Code Examples for org.apache.poi.openxml4j.opc.OPCPackage

The following are top voted examples for showing how to use org.apache.poi.openxml4j.opc.OPCPackage. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: M2Doc   File: RunProviderTests.java   Source Code and License 9 votes vote down vote up
@Test(expected = NoSuchElementException.class)
public void testAccessEmptyIterator() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenProvider iterator = new TokenProvider(document);
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
    }
}
 
Example 2
Project: iBase4J   File: Excel2007Reader.java   Source Code and License 7 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename
 * @throws Exception
 */
public void process(InputStream stream) throws Exception {
	OPCPackage pkg = OPCPackage.open(stream);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 3
Project: Gargoyle   File: DocxFileParser.java   Source Code and License 7 votes vote down vote up
public String docxFileContentParser(String fileName) {
	try {
		FileInputStream fs = new FileInputStream(new File(fileName));
		OPCPackage d = OPCPackage.open(fs);
		if (fileName.endsWith(".docx")) {
			XWPFWordExtractor xw = new XWPFWordExtractor(d);
			return xw.getText();
		} else if (fileName.endsWith(".pptx")) {
			XSLFPowerPointExtractor xp = new XSLFPowerPointExtractor(d);
			return xp.getText();
		} else if (fileName.endsWith(".xlsx")) {
			XSSFExcelExtractor xe = new XSSFExcelExtractor(d);
			xe.setFormulasNotResults(true);
			xe.setIncludeSheetNames(true);
			return xe.getText();
		}
	} catch (Exception e) {
		System.out.println("# DocxFileParser Error :" + e.getMessage());
	}
	return "";
}
 
Example 4
Project: M2Doc   File: RunProviderTests.java   Source Code and License 7 votes vote down vote up
@Test
public void testNonEmptyDoc() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenProvider iterator = new TokenProvider(document);
        XWPFRun run = iterator.next().getRun();
        assertEquals("P1Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P1Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" P1Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("", run.getText(run.getTextPosition()));
        assertTrue(!iterator.hasNext());
    }
}
 
Example 5
Project: M2Doc   File: RunProviderTests.java   Source Code and License 7 votes vote down vote up
@Test
public void testLookaheadEmptyIterator() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenProvider iterator = new TokenProvider(document);
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        iterator.next().getRun();
        assertNull(iterator.lookAhead(1));
    }
}
 
Example 6
Project: M2Doc   File: RunProviderTests.java   Source Code and License 7 votes vote down vote up
@Test
public void testNextWitLookAhead() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenProvider iterator = new TokenProvider(document);
        // CHECKSTYLE:OFF
        assertTrue(iterator.hasElements(7));
        // CHECKSTYLE:ON
        XWPFRun run;
        run = iterator.lookAhead(1).getRun();
        assertEquals("P1Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P1Run1 ", run.getText(run.getTextPosition()));
        run = iterator.lookAhead(1).getRun();
        assertEquals("P1Run2", run.getText(run.getTextPosition()));
        run = iterator.lookAhead(2).getRun();
        assertEquals(" P1Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P1Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" P1Run3", run.getText(run.getTextPosition()));
        assertTrue(iterator.hasElements(4));
    }
}
 
Example 7
Project: M2Doc   File: RunIteratorTests.java   Source Code and License 7 votes vote down vote up
@Test
public void testNonEmptyDoc() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenIterator iterator = new TokenIterator(document);
        XWPFRun run = iterator.next().getRun();
        assertEquals("P1Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P1Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" P1Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run1 ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run2", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals(" ", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("P2Run3", run.getText(run.getTextPosition()));
        run = iterator.next().getRun();
        assertEquals("", run.getText(run.getTextPosition()));
        assertTrue(!iterator.hasNext());
    }
}
 
Example 8
Project: M2Doc   File: RunIteratorTests.java   Source Code and License 7 votes vote down vote up
@Test
public void testAccessEmptyIterator() throws InvalidFormatException, IOException {
    try (FileInputStream is = new FileInputStream("resources/document/notEmpty/notEmpty-template.docx");
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);) {
        TokenIterator iterator = new TokenIterator(document);
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertNotNull(iterator.next());
        assertFalse(iterator.hasNext());
        boolean hasException = false;
        try {
            iterator.next();
        } catch (NoSuchElementException e) {
            assertTrue(e instanceof NoSuchElementException);
            hasException = true;
        }
        assertTrue(hasException);
    }
}
 
Example 9
Project: M2Doc   File: M2DocTestUtils.java   Source Code and License 7 votes vote down vote up
/**
 * Gets the textual element of the .docx at the given {@link URI}.
 * 
 * @param uriConverter
 *            the {@link URIConverter}
 * @param uri
 *            the .docx {@link URI}
 * @return the textual element of the .docx at the given {@link URI}
 */
public static String getTextContent(URIConverter uriConverter, URI uri) {
    String result = "";

    try (InputStream is = uriConverter.createInputStream(uri);
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);
            XWPFWordExtractor ex = new XWPFWordExtractor(document);) {

        result += "===== Document Text ====\n";
        result += ex.getText();
        // CHECKSTYLE:OFF
    } catch (Throwable e) {
        // CHECKSTYLE:ON
        /*
         * if for some reason we can't use POI to get the text content then move along, we'll still get the XML and hashs
         */
    }
    return result;
}
 
Example 10
Project: poiji   File: XSSFUnmarshaller.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> List<T> unmarshal(Class<T> type) {
    try (OPCPackage open = OPCPackage.open(poijiFile.file())) {

        ReadOnlySharedStringsTable readOnlySharedStringsTable = new ReadOnlySharedStringsTable(open);
        XSSFReader xssfReader = new XSSFReader(open);
        StylesTable styles = xssfReader.getStylesTable();

        SheetIterator iter = (SheetIterator) xssfReader.getSheetsData();
        int index = 0;

        while (iter.hasNext()) {
            try (InputStream stream = iter.next()) {
                if (index == options.sheetIndex()) {
                    return processSheet(styles, readOnlySharedStringsTable, type, stream);
                }
            }
            ++index;
        }
        return new ArrayList<>();
    } catch (SAXException | IOException | OpenXML4JException e) {
        throw new PoijiException("Problem occurred while reading data", e);
    }
}
 
Example 11
Project: iBase4J-Common   File: Excel2007Reader.java   Source Code and License 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename string
 * @throws Exception  if an error occurred
 */
public void process(String filename) throws Exception {
	OPCPackage pkg = OPCPackage.open(filename);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 12
Project: iBase4J-Common   File: Excel2007Reader.java   Source Code and License 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param stream
 * @throws Exception if an error occurred
 */
public void process(InputStream stream) throws Exception {
	OPCPackage pkg = OPCPackage.open(stream);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 13
Project: automat   File: Excel2007Reader.java   Source Code and License 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename
 * @throws Exception
 */
public void process(String filename) throws Exception {
	OPCPackage pkg = OPCPackage.open(filename);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 14
Project: automat   File: Excel2007Reader.java   Source Code and License 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename
 * @throws Exception
 */
public void process(InputStream stream) throws Exception {
	OPCPackage pkg = OPCPackage.open(stream);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 15
Project: iBase4J   File: Excel2007Reader.java   Source Code and License 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename
 * @throws Exception
 */
public void process(String filename) throws Exception {
	OPCPackage pkg = OPCPackage.open(filename);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 16
Project: ExcelKit   File: XlsxReader.java   Source Code and License 6 votes vote down vote up
private void processAll(OPCPackage pkg)
		throws IOException, OpenXML4JException, InvalidFormatException, SAXException {
	XSSFReader xssfReader = new XSSFReader(pkg);
	mStylesTable = xssfReader.getStylesTable();
	SharedStringsTable sst = xssfReader.getSharedStringsTable();
	XMLReader parser = this.fetchSheetParser(sst);
	Iterator<InputStream> sheets = xssfReader.getSheetsData();
	while (sheets.hasNext()) {
		mCurrentRowIndex = 0;
		mSheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
	pkg.close();
}
 
Example 17
Project: ExcelKit   File: XlsxReader.java   Source Code and License 6 votes vote down vote up
private void processBySheet(int sheetIndex, OPCPackage pkg)
		throws IOException, OpenXML4JException, InvalidFormatException, SAXException {
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();

	XMLReader parser = fetchSheetParser(sst);

	// rId2 found by processing the Workbook
	// 根据 rId# 或 rSheet# 查找sheet
	InputStream sheet = r.getSheet("rId" + (sheetIndex + 1));
	mSheetIndex++;
	InputSource sheetSource = new InputSource(sheet);
	parser.parse(sheetSource);
	sheet.close();
	pkg.close();
}
 
Example 18
Project: JAVA-   File: Excel2007Reader.java   Source Code and License 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename
 * @throws Exception
 */
public void process(String filename) throws Exception {
	OPCPackage pkg = OPCPackage.open(filename);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 19
Project: JAVA-   File: Excel2007Reader.java   Source Code and License 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename
 * @throws Exception
 */
public void process(InputStream stream) throws Exception {
	OPCPackage pkg = OPCPackage.open(stream);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 20
Project: GraphicsViewJambi   File: ImportNetworkFromExcel.java   Source Code and License 6 votes vote down vote up
/**
 * ImportFromXLSX
 * @param inputStream
 * @param sheetNumber
 * @return
 * @throws InvalidFormatException
 * @throws IOException
 */
public static DenseObjectMatrix2D importFromXLSX(final InputStream inputStream, final int sheetNumber)
		throws InvalidFormatException, IOException 
{
	final OPCPackage pkg = OPCPackage.open(inputStream);
	final XSSFWorkbook workbook = new XSSFWorkbook(pkg);
	final DenseObjectMatrix2D matrix = importFromWorkbook(workbook, sheetNumber);
	pkg.close();
	
	return matrix;
}
 
Example 21
Project: bdf2   File: XSSFParser.java   Source Code and License 6 votes vote down vote up
public void execute(InputStream inputStream, IParseExcelRowMapper parseExcelRowMapper) throws Exception {
	OPCPackage pkg = OPCPackage.open(inputStream);
	XSSFReader xssfReader = new XSSFReader(pkg);
	sst = xssfReader.getSharedStringsTable();
	stylesTable = xssfReader.getStylesTable();

	SAXParserFactory saxFactory = SAXParserFactory.newInstance();
	SAXParser saxParser = saxFactory.newSAXParser();
	XMLReader parser = saxParser.getXMLReader();
	parser.setContentHandler(new XSSFParserHandler());

	this.parseExcelRowMapper = parseExcelRowMapper;

	XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
	while (iter.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = iter.next();
		sheetName = iter.getSheetName();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}

}
 
Example 22
Project: semtool   File: LowMemXlsReader.java   Source Code and License 6 votes vote down vote up
public LowMemXlsReader( InputStream stream ) throws IOException {
	log.debug( "reading with lo-mem xls reader" );
	sharedStrings = new ArrayList<>();
	try {
		pkg = OPCPackage.open( stream );
		reader = new XSSFReader( pkg );

		styles = reader.getStylesTable();

		sheetNameIdLkp = readSheetInfo( reader );
		populateSharedStrings( reader );
	}
	catch ( OpenXML4JException e ) {
		throw new IOException( "unexpected error" + e.getLocalizedMessage(), e );
	}
}
 
Example 23
Project: poix   File: SaxReadExcel.java   Source Code and License 6 votes vote down vote up
private <T> List<T> readExcel(OPCPackage opcPackage, Class<?> pojoClass, ImportParams params,
                              ISaxRowRead rowRead, IExcelReadRowHanlder hanlder) {
    try {
        XSSFReader xssfReader = new XSSFReader(opcPackage);
        SharedStringsTable sst = xssfReader.getSharedStringsTable();
        if (rowRead == null) {
            rowRead = new SaxRowRead(pojoClass, params, hanlder);
        }
        XMLReader parser = fetchSheetParser(sst, rowRead);
        Iterator<InputStream> sheets = xssfReader.getSheetsData();
        int sheetIndex = 0;
        while (sheets.hasNext() && sheetIndex < params.getSheetNum()) {
            sheetIndex++;
            InputStream sheet = sheets.next();
            InputSource sheetSource = new InputSource(sheet);
            parser.parse(sheetSource);
            sheet.close();
        }
        return rowRead.getList();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new ExcelImportException("SAX导入数据失败");
    }
}
 
Example 24
Project: easypoi   File: SaxReadExcel.java   Source Code and License 6 votes vote down vote up
private <T> List<T> readExcel(OPCPackage opcPackage, Class<?> pojoClass, ImportParams params,
                              ISaxRowRead rowRead, IExcelReadRowHanlder hanlder) {
    try {
        XSSFReader xssfReader = new XSSFReader(opcPackage);
        SharedStringsTable sst = xssfReader.getSharedStringsTable();
        if (rowRead == null) {
            rowRead = new SaxRowRead(pojoClass, params, hanlder);
        }
        XMLReader parser = fetchSheetParser(sst, rowRead);
        Iterator<InputStream> sheets = xssfReader.getSheetsData();
        int sheetIndex = 0;
        while (sheets.hasNext() && sheetIndex < params.getSheetNum()) {
            sheetIndex++;
            InputStream sheet = sheets.next();
            InputSource sheetSource = new InputSource(sheet);
            parser.parse(sheetSource);
            sheet.close();
        }
        return rowRead.getList();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new ExcelImportException("SAX导入数据失败");
    }
}
 
Example 25
Project: eid-applet   File: OOXMLSignatureVerifierTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testOPC() throws Exception {
	// setup
	InputStream inputStream = OOXMLSignatureVerifierTest.class.getResourceAsStream("/hello-world-signed.docx");

	// operate
	OPCPackage opcPackage = OPCPackage.open(inputStream);

	ArrayList<PackagePart> parts = opcPackage.getParts();
	for (PackagePart part : parts) {
		LOG.debug("part name: " + part.getPartName().getName());
		LOG.debug("part content type: " + part.getContentType());
	}

	ArrayList<PackagePart> signatureParts = opcPackage
			.getPartsByContentType("application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml");
	assertFalse(signatureParts.isEmpty());

	PackagePart signaturePart = signatureParts.get(0);
	LOG.debug("signature part class type: " + signaturePart.getClass().getName());

	PackageDigitalSignatureManager packageDigitalSignatureManager = new PackageDigitalSignatureManager();
	// yeah... POI implementation still missing
}
 
Example 26
Project: bingexcel   File: DefaultXSSFSaxHandler.java   Source Code and License 6 votes vote down vote up
public DefaultXSSFSaxHandler(File file, ExcelReadListener excelReader,
		boolean ignoreNumFormat) throws InvalidFormatException {
	
	
	try {
		this.pkg = OPCPackage.open(file, PackageAccess.READ);
		this.excelReader = excelReader;
		this.ignoreNumFormat = ignoreNumFormat;
		this.handler = new DefaultSheetContentsHandler(
				excelReader);
	} catch (IllegalArgumentException  e) {
		//异常是open方法抛出的。确保io关闭
		pkg.revert();
		throw e;
	}
}
 
Example 27
Project: bingexcel   File: ExcelReaderFactory.java   Source Code and License 6 votes vote down vote up
/**
 * @param file
 * @param excelReader
 * @param ignoreNumFormat  是否忽略数据格式  (default=false,按照格式读取)
 * @return
 * @throws Exception
 */
public static ReadHandler create(File file, ExcelReadListener excelReader,
		boolean ignoreNumFormat) throws Exception {
	if (!file.exists()) {
		throw new FileNotFoundException(file.toString());
	}
	try {
		POIFSFileSystem fs = new POIFSFileSystem(file);
		return create(fs, excelReader, ignoreNumFormat);
	} catch (OfficeXmlFileException e) {
		OPCPackage pkg = OPCPackage.open(file, PackageAccess.READ);
		try {
			return create(pkg, excelReader, ignoreNumFormat);
		} catch (IllegalArgumentException | IOException e1) {
			pkg.revert();
			throw e1;
		}
	}

}
 
Example 28
Project: bingexcel   File: ExcelReaderFactory.java   Source Code and License 6 votes vote down vote up
/**
 * @param inp
 * @param excelReader
 * @param ignoreNumFormat 是否忽略数据格式  (default=false,按照格式读取) 
 * @return  jie
 * @throws InvalidFormatException
 * @throws IOException
 * @throws SQLException
 */
public static ReadHandler create(InputStream inp,
		ExcelReadListener excelReader, boolean ignoreNumFormat)
		throws InvalidFormatException, IOException, SQLException {
	 // If clearly doesn't do mark/reset, wrap up
       if (! inp.markSupported()) {
           inp = new PushbackInputStream(inp, 8);
       }

       // Ensure that there is at least some data there
       byte[] header8 = IOUtils.peekFirst8Bytes(inp);

       // Try to create
       if (POIFSFileSystem.hasPOIFSHeader(header8)) {
           POIFSFileSystem fs = new POIFSFileSystem(inp);
           return create(fs, excelReader, ignoreNumFormat);
       }
       if (POIXMLDocument.hasOOXMLHeader(inp)) {
            OPCPackage pkg = OPCPackage.open(inp);
            return create(pkg, excelReader, ignoreNumFormat);
       }
       throw new InvalidFormatException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
   

}
 
Example 29
Project: Improve   File: XxlsAbstract.java   Source Code and License 6 votes vote down vote up
public void processOneSheet(String filename, int sheetId) throws Exception {
	OPCPackage pkg = OPCPackage.open(filename);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();

	XMLReader parser = fetchSheetParser(sst);

	// rId2 found by processing the Workbook
	// 根据 rId# 或 rSheet# 查找sheet
	InputStream sheet2 = r.getSheet("rId" + sheetId);
	sheetIndex++;
	InputSource sheetSource = new InputSource(sheet2);
	parser.parse(sheetSource);
	sheet2.close();
	pkg.close();
}
 
Example 30
Project: Improve   File: XxlsAbstract.java   Source Code and License 6 votes vote down vote up
/**
 * 遍历 excel 文件
 */
public void process(String filename) throws Exception {
	OPCPackage pkg = OPCPackage.open(filename);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();

	XMLReader parser = fetchSheetParser(sst);

	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
	pkg.close();
}
 
Example 31
Project: poi-visio   File: XmlVisioDocument.java   Source Code and License 6 votes vote down vote up
public XmlVisioDocument(OPCPackage pkg) throws IOException {
	super(pkg, CORE_DOCUMENT);
	
	VisioDocumentType document;
	
	try {
		document = VisioDocumentDocument1.Factory.parse(getPackagePart().getInputStream()).getVisioDocument();	
	} catch (XmlException | IOException e) {
		throw new POIXMLException(e);
	}
	
	_document = new XDGFDocument(document);
	
	//build a tree of POIXMLDocumentParts, this document being the root
       load(new XDGFFactory(_document));
}
 
Example 32
Project: sumo-report-generator   File: ExcelWorkbookGenerator.java   Source Code and License 6 votes vote down vote up
private Workbook generateWorkbookWithSheets(ReportConfig reportConfig) throws IOException, InvalidFormatException {
    if (!reportConfig.isAppendToDestination()) {
        LOGGER.debug("creating empty workbook with sheets");
        Workbook workbook = new XSSFWorkbook();
        FileOutputStream fileOut = new FileOutputStream(reportConfig.getDestinationFile());
        generateSheets(reportConfig, workbook);
        workbook.write(fileOut);
        fileOut.close();
        LOGGER.debug("workbook created");
        return workbook;
    } else {
        LOGGER.debug("will append to destination file");
        File destFile = new File(reportConfig.getDestinationFile());
        FileInputStream fileInputStream = new FileInputStream(destFile);
        OPCPackage opc = OPCPackage.open(fileInputStream);
        return WorkbookFactory.create(opc);
    }
}
 
Example 33
Project: translationstudio8   File: Xlsx2TmxHelper.java   Source Code and License 6 votes vote down vote up
public void parseXlsxFileAndWriteTmxBody(String fileName, AbstractWriter tmxWriter, IProgressMonitor monitor)
		throws ParserConfigurationException, SAXException, IOException, OpenXML4JException {
	this.tmxWriter = tmxWriter;
	this.monitor = monitor;
	File file = new File(fileName);
	long length = file.length();
	monitor.beginTask("", countTotal(length));
	OPCPackage p = OPCPackage.open(fileName, PackageAccess.READ);
	ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(p);
	XSSFReader xssfReader = new XSSFReader(p);
	XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
	try {
		while (iter.hasNext()) {
			InputStream stream = iter.next();
			parse(stream, strings, tmxWriter);
			stream.close();
			// 目前只处理第一个sheet
			break;
		}
	} finally {
		p.close();
	}

	monitor.done();
}
 
Example 34
Project: translationstudio8   File: XlsxRowReader.java   Source Code and License 6 votes vote down vote up
public void readRows(IProgressMonitor monitor) throws ParserConfigurationException, SAXException, IOException, OpenXML4JException {
	monitor.beginTask("", 10);
	monitor.worked(1);
	OPCPackage p = OPCPackage.open(xlsxFile, PackageAccess.READ);
	ReadOnlySharedStringsTable shareString = new ReadOnlySharedStringsTable(p);
	XSSFReader xssfReader = new XSSFReader(p);
	XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
	try {
		while (iter.hasNext()) {
			InputStream stream = iter.next();
			readCells(stream, shareString, new SubProgressMonitor(monitor, 9));
			stream.close();
			// 目前只处理第一个sheet
			break;
		}
	} finally {
		p.close();
		monitor.done();
	}
}
 
Example 35
Project: tmxeditor8   File: Xlsx2TmxHelper.java   Source Code and License 6 votes vote down vote up
public void parseXlsxFileAndWriteTmxBody(String fileName, AbstractWriter tmxWriter, IProgressMonitor monitor)
		throws ParserConfigurationException, SAXException, IOException, OpenXML4JException {
	this.tmxWriter = tmxWriter;
	this.monitor = monitor;
	File file = new File(fileName);
	long length = file.length();
	monitor.beginTask("", countTotal(length));
	OPCPackage p = OPCPackage.open(fileName, PackageAccess.READ);
	ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(p);
	XSSFReader xssfReader = new XSSFReader(p);
	XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
	try {
		while (iter.hasNext()) {
			InputStream stream = iter.next();
			parse(stream, strings, tmxWriter);
			stream.close();
			// 目前只处理第一个sheet
			break;
		}
	} finally {
		p.close();
	}

	monitor.done();
}
 
Example 36
Project: bachelor   File: ParseBigDatasExcel.java   Source Code and License 6 votes vote down vote up
/** 
 * 读取第一个工作簿的入口方法 
 * @param path 
 */  
public List<?> readOneSheet(InputStream input,String excelType) throws Exception {  
    OPCPackage pkg = OPCPackage.open(input);    
    XSSFReader r = new XSSFReader(pkg);  
    SharedStringsTable sst = r.getSharedStringsTable();  
    
    if(excelType.equals(Constant.ENITY_TYPE_ROLEPERSIONAL)){
    	
    	lists = new ArrayList<AuthRoleUser>();
    }
    
    XMLReader parser = fetchSheetParser(sst);  
          
    InputStream sheet = r.getSheet("rId1");  
  
    InputSource sheetSource = new InputSource(sheet);  
    parser.parse(sheetSource);  
    
    
    if(excelType.equals(Constant.ENITY_TYPE_ROLEPERSIONAL)){

    	return lists;
    }
    sheet.close();        
    return lists;
}
 
Example 37
Project: bachelor   File: ParseBigDatasExcel.java   Source Code and License 6 votes vote down vote up
/** 
 * 读取所有工作簿的入口方法 
 * @param path 
 * @throws Exception 
 */  
public void process(String path) throws Exception {  
    OPCPackage pkg = OPCPackage.open(path);  
    XSSFReader r = new XSSFReader(pkg);  
    SharedStringsTable sst = r.getSharedStringsTable();  
  
    XMLReader parser = fetchSheetParser(sst);  
  
    Iterator<InputStream> sheets = r.getSheetsData();  
    while (sheets.hasNext()) {  
        curRow = 0;  
        sheetIndex++;  
        InputStream sheet = sheets.next();  
        InputSource sheetSource = new InputSource(sheet);  
        parser.parse(sheetSource);  
        sheet.close();  
    }  
}
 
Example 38
Project: esup-dematec   File: WordParser.java   Source Code and License 6 votes vote down vote up
public void  modifyWord(InputStream docx, Map<String, String> textMap, OutputStream out) {
	try {
		XWPFDocument doc = new XWPFDocument(OPCPackage.open(docx));

		// tentative avec les noms {{}}
		for (XWPFParagraph p : doc.getParagraphs()) {

			for(CTBookmark bookmark: p.getCTP().getBookmarkStartList()) {
				log.trace(bookmark.getName());
				for(String key : textMap.keySet()) {
					String cleanKey = StringUtils.stripAccents(key);
					cleanKey = cleanKey.replaceAll(" ", "_");
					cleanKey = cleanKey.replaceAll( "\\W", "");
					if(bookmark.getName().equalsIgnoreCase(cleanKey)) {
						Node nextNode = bookmark.getDomNode().getNextSibling();
		                while(nextNode != null &&  nextNode.getNodeName() != null &&  !(nextNode.getNodeName().contains("bookmarkEnd"))) { 
		                    p.getCTP().getDomNode().removeChild(nextNode); 
		                    nextNode = bookmark.getDomNode().getNextSibling(); 
		                } 
						XWPFRun run = p.createRun();
						run.setText(textMap.get(key));
						p.getCTP().getDomNode().insertBefore(run.getCTR().getDomNode(), nextNode); 
					}
				}
			}
		}

		doc.write(out);
	} catch(Exception e) {
		log.error("Pb durant la modification du document word", e);
	}

}
 
Example 39
Project: nextreports-engine   File: XlsxExporter.java   Source Code and License 6 votes vote down vote up
protected void initExport() throws QueryException {    	
 	if (hasTemplate()) {    		
 		try {    		
 			if (bean.getReportLayout().getTemplateName().endsWith(".xlsm")) {
 				wb = new XSSFWorkbook(OPCPackage.open(getTemplateInputStream()));
 			} else {    			
 				wb = new XSSFWorkbook(getTemplateInputStream());
 			}
} catch (Exception e) {
	e.printStackTrace();
	LOG.error(e.getMessage(), e);
	wb = new XSSFWorkbook();   
}
 	} else {
 		wb = new XSSFWorkbook();
 	}
 }
 
Example 40
Project: metamodel   File: XlsxSpreadsheetReaderDelegate.java   Source Code and License 6 votes vote down vote up
@Override
public Schema createSchema(String schemaName) throws Exception {
    final MutableSchema schema = new MutableSchema(schemaName);
    final OPCPackage pkg = openOPCPackage();
    try {
        final XSSFReader xssfReader = new XSSFReader(pkg);

        final XlsxWorkbookToTablesHandler workbookToTables = new XlsxWorkbookToTablesHandler(schema,
                _tableNamesToInternalIds);
        buildTables(xssfReader, workbookToTables);

        for (Entry<String, String> entry : _tableNamesToInternalIds.entrySet()) {

            final String tableName = entry.getKey();
            final String relationshipId = entry.getValue();

            final MutableTable table = (MutableTable) schema.getTableByName(tableName);

            buildColumns(table, relationshipId, xssfReader);
        }
    } finally {
        pkg.revert();
    }
    return schema;
}