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

The following examples show how to use org.apache.poi.openxml4j.opc.OPCPackage. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: o2oa   Author: o2oa   File: Excel2007Reader.java    License: GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * @param filename
 * @param fileKey 
 * @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 #2
Source Project: o2oa   Author: o2oa   File: Excel2007Reader.java    License: GNU Affero General Public License v3.0 7 votes vote down vote up
/**只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
 * @param filename
 * @param sheetId
 * @throws Exception
 */
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);
	
	// 根据 rId# 或 rSheet# 查找sheet
	InputStream sheet2 = r.getSheet( "rId"+sheetId);
	sheetIndex++;
	InputSource sheetSource = new InputSource(sheet2);
	parser.parse(sheetSource);
	sheet2.close();
}
 
Example #3
Source Project: easyexcel   Author: alibaba   File: WriteContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
private POIFSFileSystem openFileSystemAndEncrypt(File file) throws Exception {
    POIFSFileSystem fileSystem = new POIFSFileSystem();
    Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor();
    encryptor.confirmPassword(writeWorkbookHolder.getPassword());
    OPCPackage opcPackage = null;
    try {
        opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE);
        OutputStream outputStream = encryptor.getDataStream(fileSystem);
        opcPackage.save(outputStream);
    } finally {
        if (opcPackage != null) {
            opcPackage.close();
        }
    }
    return fileSystem;
}
 
Example #4
Source Project: M2Doc   Author: ObeoNetwork   File: M2DocTestUtils.java    License: Eclipse Public License 1.0 6 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 #5
Source Project: easyexcel   Author: alibaba   File: Poi3Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void Encryption() throws Exception {
    String file = TestFileUtil.getPath() + "large" + File.separator + "large07.xlsx";
    POIFSFileSystem fs = new POIFSFileSystem();
    EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
    Encryptor enc = info.getEncryptor();
    enc.confirmPassword("foobaa");
    OPCPackage opc = OPCPackage.open(new File(file), PackageAccess.READ_WRITE);
    OutputStream os = enc.getDataStream(fs);
    opc.save(os);
    opc.close();

    // Write out the encrypted version
    FileOutputStream fos = new FileOutputStream("D:\\test\\99999999999.xlsx");
    fs.writeFilesystem(fos);
    fos.close();
    fs.close();

}
 
Example #6
Source Project: o2oa   Author: o2oa   File: Excel2007Reader.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * @param filename
 * @param fileKey 
 * @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 #7
Source Project: o2oa   Author: o2oa   File: Excel2007Reader.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * @param is
 * @param fileKey 
 * @throws Exception
 */
public void process( InputStream is ) throws Exception {
	OPCPackage pkg = OPCPackage.open( is );
	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 #8
Source Project: o2oa   Author: o2oa   File: Excel2007Reader.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * @param is
 * @param fileKey 
 * @throws Exception
 */
public void process( InputStream is ) throws Exception {
	OPCPackage pkg = OPCPackage.open( is );
	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 #9
Source Project: o2oa   Author: o2oa   File: Excel2007Reader.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * @param filename
 * @param fileKey 
 * @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 #10
Source Project: o2oa   Author: o2oa   File: Excel2007Reader.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * @param filename
 * @param fileKey 
 * @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 #11
Source Project: o2oa   Author: o2oa   File: Excel2007Reader.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * @param filename
 * @param fileKey 
 * @throws Exception
 */
public void process( InputStream is ) throws Exception {
	OPCPackage pkg = OPCPackage.open( is );
	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
Source Project: translationstudio8   Author: heartsome   File: Xlsx2TmxHelper.java    License: GNU General Public License v2.0 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 #13
Source Project: o2oa   Author: o2oa   File: Excel2007Reader.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * @param filename
 * @param fileKey 
 * @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
Source Project: DocBleach   Author: docbleach   File: OOXMLBleach.java    License: MIT License 6 votes vote down vote up
void sanitize(BleachSession session, OPCPackage pkg, PackagePart part) {
  LOGGER.trace("Part name: {}", part.getPartName());

  String contentType = part.getContentType();
  LOGGER.debug("Content type: {} for part {}", contentType, part.getPartName());

  // Sample content types:
  // vnd.ms-word.vbaData+xml, vnd.ms-office.vbaProject
  // cf https://msdn.microsoft.com/fr-fr/library/aa338205(v=office.12).aspx
  ContentType type = part.getContentTypeDetails();
  if (isForbiddenType(type) || isStrangeContentType(type)) {
    LOGGER.debug(SUSPICIOUS_OOXML_FORMAT, contentType, part.getPartName(), part.getSize());
    deletePart(pkg, part.getPartName());

    Threat threat = Threat.builder()
        .type(ThreatType.ACTIVE_CONTENT)
        .severity(ThreatSeverity.HIGH)
        .action(ThreatAction.REMOVE)
        .location(part.getPartName().getName())
        .details("Forbidden content type: " + type)
        .build();

    session.recordThreat(threat);
  }
}
 
Example #15
Source Project: javautils   Author: followwwind   File: XSSFUtil.java    License: Apache License 2.0 6 votes vote down vote up
public void processAllSheets(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()) {
        System.out.println("Processing new sheet:\n");
        InputStream sheet = sheets.next();
        InputSource sheetSource = new InputSource(sheet);
        parser.parse(sheetSource);
        sheet.close();
        System.out.println("");
    }
}
 
Example #16
Source Project: M2Doc   Author: ObeoNetwork   File: RunProviderTests.java    License: Eclipse Public License 1.0 6 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 #17
Source Project: M2Doc   Author: ObeoNetwork   File: RunProviderTests.java    License: Eclipse Public License 1.0 6 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 #18
Source Project: M2Doc   Author: ObeoNetwork   File: RunProviderTests.java    License: Eclipse Public License 1.0 6 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 #19
Source Project: M2Doc   Author: ObeoNetwork   File: RunIteratorTests.java    License: Eclipse Public License 1.0 6 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 #20
Source Project: onetwo   Author: wayshall   File: ExcelUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static OPCPackage readPackage(String path){
	try {
		OPCPackage pack = POIXMLDocument.openPackage(path);
		return pack;
	} catch (IOException e) {
		throw new RuntimeException("read word file["+path+"] error:"+e.getMessage());
	}
}
 
Example #21
Source Project: frpMgr   Author: Zo3i   File: ExcelReader.java    License: MIT License 5 votes vote down vote up
/**
 * 只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
 * @param filename
 * @param sheetId
 * @throws Exception
 */
public void process(String filename, int sheetId) throws Exception {
	OPCPackage pkg = OPCPackage.open(filename);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	// 根据 rId# 或 rSheet# 查找sheet
	InputStream sheet2 = r.getSheet("rId" + sheetId);
	sheetIndex++;
	InputSource sheetSource = new InputSource(sheet2);
	parser.parse(sheetSource);
	sheet2.close();
}
 
Example #22
Source Project: opencards   Author: holgerbrandl   File: ConvertPPTX2PNG.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) throws IOException, InvalidFormatException {
        FileInputStream is = new FileInputStream("/Users/brandl/Dropbox/private/oc2/testdata/experimental design.pptx");

        XMLSlideShow ppt2 = new XMLSlideShow(OPCPackage.open("/Users/brandl/Dropbox/private/oc2/testdata/experimental design.pptx"));
        XSLFSlide slide1 = ppt2.getSlides().get(0);
//        slide1.get

        HSLFSlideShow ppt = new HSLFSlideShow(is);
//
        HSLFSlide slide2 = ppt.getSlides().get(1);


        is.close();

        Dimension pgsize = ppt.getPageSize();

        java.util.List<HSLFSlide> slides = ppt.getSlides();

        for (int i = 0; i < slides.size(); i++) {

            BufferedImage img = new BufferedImage(pgsize.width, pgsize.height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = img.createGraphics();
            //clear the drawing area
            graphics.setPaint(Color.white);
            graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

            //render
            slides.get(i).draw(graphics);

            //save the output
            FileOutputStream out = new FileOutputStream("slide-" + (i + 1) + ".png");
            javax.imageio.ImageIO.write(img, "png", out);
            out.close();
        }
    }
 
Example #23
Source Project: ontopia   Author: ontopia   File: OOXMLWordFormatModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void readContent(ClassifiableContentIF cc, TextHandlerIF handler) {
  try {
    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);
  }    
}
 
Example #24
Source Project: dk-fitting   Author: dkhadoop   File: OfficeUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String Parse07(String FilePath) throws IOException, XmlException, OpenXML4JException{
    String text2007=null;
    try{
        OPCPackage opcPackage = POIXMLDocument.openPackage(FilePath);
        POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
        text2007 = extractor.getText();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return text2007;
}
 
Example #25
Source Project: easyexcel   Author: Dorae132   File: XlsxHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename
 * @throws IOException
 * @throws OpenXML4JException
 * @throws SAXException
 * @throws Exception
 */
public void process(String filename) throws IOException, OpenXML4JException, SAXException {
    OPCPackage pkg = null;
    try {
	    pkg = OPCPackage.open(filename);
        XSSFReader xssfReader = new XSSFReader(pkg);
        stylesTable = xssfReader.getStylesTable();
        SharedStringsTable sst = xssfReader.getSharedStringsTable();
        XMLReader parser = this.fetchSheetParser(sst);
        Iterator<InputStream> sheets = xssfReader.getSheetsData();
   		while (sheets.hasNext()) {
   			currRowIndex = 0;
   			sheetIndex++;
   			InputStream sheet = null;
   			try {
   			    sheet = sheets.next();
   			    InputSource sheetSource = new InputSource(sheet);
   			    parser.parse(sheetSource);
   			} finally {
   			    sheet.close();
               }
   		}
   		while (!context.fileEnd());
	} finally {
           pkg.close();
       }
}
 
Example #26
Source Project: autopoi   Author: zhangdaiscott   File: SaxReadExcel.java    License: Apache License 2.0 5 votes vote down vote up
public <T> List<T> readExcel(InputStream inputstream, Class<?> pojoClass, ImportParams params, ISaxRowRead rowRead, IExcelReadRowHanlder hanlder) {
	try {
		OPCPackage opcPackage = OPCPackage.open(inputstream);
		return readExcel(opcPackage, pojoClass, params, rowRead, hanlder);
	} catch (Exception e) {
		LOGGER.error(e.getMessage(), e);
		throw new ExcelImportException(e.getMessage());
	}
}
 
Example #27
Source Project: M2Doc   Author: ObeoNetwork   File: M2DocUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Parses a document for {@link UserContent} and returns the {@link DocumentTemplate} resulting from
 * this parsing.
 * 
 * @param uriConverter
 *            the {@link URIConverter uri converter} to use.
 * @param documentURI
 *            URI for the document
 * @param queryEnvironment
 *            the {@link IQueryEnvironment}
 * @return the {@link DocumentTemplate} resulting from parsing the specified
 *         document
 * @throws DocumentParserException
 *             if a problem occurs while parsing the document.
 */
@SuppressWarnings("resource")
public static DocumentTemplate parseUserContent(URIConverter uriConverter, URI documentURI,
        IQueryEnvironment queryEnvironment) throws DocumentParserException {
    final DocumentTemplate result = (DocumentTemplate) EcoreUtil.create(TemplatePackage.Literals.DOCUMENT_TEMPLATE);
    final ResourceImpl r = new ResourceImpl(documentURI);

    try {
        // resources are closed in DocumentTemplate.close()
        final InputStream is = uriConverter.createInputStream(documentURI);
        final OPCPackage oPackage = OPCPackage.open(is);
        final XWPFDocument document = new XWPFDocument(oPackage);
        r.getContents().add(result);
        final BodyGeneratedParser parser = new BodyGeneratedParser(document, queryEnvironment);
        result.setBody(parser.parseBlock(null));
        result.setInputStream(is);
        result.setOpcPackage(oPackage);
        result.setDocument(document);
        for (XWPFFooter footer : document.getFooterList()) {
            final BodyGeneratedParser footerParser = new BodyGeneratedParser(footer, queryEnvironment);
            result.getFooters().add(footerParser.parseBlock(null));
        }
        for (XWPFHeader header : document.getHeaderList()) {
            final BodyGeneratedParser headerParser = new BodyGeneratedParser(header, queryEnvironment);
            result.getHeaders().add(headerParser.parseBlock(null));
        }

    } catch (IOException e) {
        throw new DocumentParserException("Unable to open " + documentURI, e);
    } catch (InvalidFormatException e1) {
        throw new DocumentParserException("Invalid .docx format " + documentURI, e1);
    }

    return result;
}
 
Example #28
Source Project: poiji   Author: ozlerhakan   File: XSSFUnmarshallerFile.java    License: MIT License 5 votes vote down vote up
@Override
public <T> void returnFromExcelFile(Class<T> type, Consumer<? super T> consumer) {

    try (OPCPackage open = OPCPackage.open(poijiFile.file(), PackageAccess.READ)) {

        unmarshal0(type, consumer, open);

    } catch (ParserConfigurationException | SAXException | IOException | OpenXML4JException e) {
        throw new PoijiException("Problem occurred while reading data", e);
    }
}
 
Example #29
Source Project: poiji   Author: ozlerhakan   File: HSSFPropertyStream.java    License: MIT License 5 votes vote down vote up
@Override
public <T> T returnFromExcelFile(Class<T> type) {
    try (OPCPackage open = OPCPackage.open(inputStream)) {
        PropertyHandler propertyHandler = new PropertyHandler();
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(open);
        return propertyHandler.unmarshal(type, xssfWorkbook.getProperties());
    } catch (IOException | OpenXML4JException e) {
        throw new PoijiException("Problem occurred while reading data", e);
    }
}
 
Example #30
Source Project: poiji   Author: ozlerhakan   File: XSSFUnmarshallerStream.java    License: MIT License 5 votes vote down vote up
@Override
public <T> void returnFromExcelFile(Class<T> type, Consumer<? super T> consumer) {

    try (OPCPackage open = OPCPackage.open(poijiInputStream.stream())) {

        unmarshal0(type, consumer, open);

    } catch (ParserConfigurationException | SAXException | IOException | OpenXML4JException e) {
        throw new PoijiException("Problem occurred while reading data", e);
    }
}