public void TestCreateFromStream() { using (Stream s = new FileStream(TESTFILE_DIR + "test002.docx", FileMode.Open)) { OPCPackage package = new OPCPackage(s); } }
public void TestCreateFromNonZip() { using (Stream s = new FileStream(TESTFILE_DIR + "document1.xml", FileMode.Open)) { OPCPackage package = new OPCPackage(s); } }
public void TestGetContentTypes() { using (Stream s = new FileStream(TESTFILE_DIR + "test002.docx", FileMode.Open)) { OPCPackage package = new OPCPackage(s); List<ContentTypeInfo> types = package.GetContentTypes(); Assert.AreEqual(14, types.Count, "expected to find 14 contentTypes in the package"); Assert.AreEqual("/word/footnotes.xml", types[0].Name); Assert.AreEqual("application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml", types[0].ContentType); } }
public void TestGetDefaultTypes() { using (Stream s = new FileStream(TESTFILE_DIR + "test002.docx", FileMode.Open)) { OPCPackage package = new OPCPackage(s); List<DefaultInfo> defaults = package.GetDefaultTypes(); Assert.AreEqual(2, defaults.Count, "expected to find 2 defaults in the package"); Assert.AreEqual("xml", defaults[1].Extension); Assert.AreEqual("application/xml", defaults[1].ContentType); } }
/** * Constructor. Parses the content of the specified input stream. * * @param in * If different of <i>null</i> then the content types part is * retrieve and parse. * @throws InvalidFormatException * If the content types part content is not valid. */ public ContentTypeManager(Stream in1, OPCPackage pkg) { this.container = pkg; this.defaultContentType = new SortedList<String, String>(); if (in1 != null) { try { ParseContentTypesFile(in1); } catch (InvalidFormatException ex) { throw new InvalidFormatException("Can't read content types part !", ex); } } }
public static OpenXmlFormat Resolve(Stream inputStream) { try { var copy = new MemoryStream(); inputStream.CopyTo(copy); using (var inputPackage = new OPCPackage(copy)) { return OpenXmlFormatIdentifier.Resolve(inputPackage.RootPart.Relationships); } } catch (Exception e) { Logger.LogError(e); } Logger.LogError("Failed to determine the Open XML format"); return OpenXmlFormat.Unknown; }
public void TestGetRelationships() { using (Stream s = new FileStream(TESTFILE_DIR + "test002.docx", FileMode.Open)) { OPCPackage package = new OPCPackage(s); List<PartInfo> rels = package.GetRelatedObjects(); Assert.AreEqual(4, rels.Count, "Expected to load 4 relationship"); PartInfo piWordDoc = rels[2]; Assert.AreEqual("word/document.xml", piWordDoc.Target); rels = piWordDoc.GetRelatedObjects(); Assert.AreEqual(12, rels.Count, "Expected to load 12 relationships for the document.xml part"); Assert.IsFalse(rels[0].External); Assert.AreEqual("comments.xml", rels[0].Target); Assert.IsTrue(rels[2].External); Assert.AreEqual(@"file:///\\wsstorage\qashared\generic\workshare.1.doc", rels[2].Target); } }
public OPCParser(OPCPackage pkg) : base(pkg) { }
public XSSFExcelExtractor(OPCPackage Container) : this(new XSSFWorkbook(Container)) { }
public void TestCreateRelationsFromScratch() { MemoryStream baos = new MemoryStream(); OPCPackage pkg = OPCPackage.Create(baos); PackagePart partA = pkg.CreatePart(PackagingUriHelper.CreatePartName("/partA"), "text/plain"); PackagePart partB = pkg.CreatePart(PackagingUriHelper.CreatePartName("/partB"), "image/png"); Assert.IsNotNull(partA); Assert.IsNotNull(partB); // Internal partA.AddRelationship(partB.PartName, TargetMode.Internal, "http://example/Rel"); // External partA.AddExternalRelationship("http://poi.apache.org/", "http://example/poi"); partB.AddExternalRelationship("http://poi.apache.org/ss/", "http://example/poi/ss"); // Check as expected currently Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.ToString()); Assert.AreEqual("http://poi.apache.org/", partA.GetRelationship("rId2").TargetUri.ToString()); Assert.AreEqual("http://poi.apache.org/ss/", partB.GetRelationship("rId1").TargetUri.ToString()); // Save, and re-load pkg.Close(); MemoryStream bais = new MemoryStream(baos.ToArray()); pkg = OPCPackage.Open(bais); partA = pkg.GetPart(PackagingUriHelper.CreatePartName("/partA")); partB = pkg.GetPart(PackagingUriHelper.CreatePartName("/partB")); // Check the relations Assert.AreEqual(2, partA.Relationships.Size); Assert.AreEqual(1, partB.Relationships.Size); Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.OriginalString); Assert.AreEqual("http://poi.apache.org/", partA.GetRelationship("rId2").TargetUri.ToString()); Assert.AreEqual("http://poi.apache.org/ss/", partB.GetRelationship("rId1").TargetUri.ToString()); // Check core too Assert.AreEqual("/docProps/core.xml", pkg.GetRelationshipsByType( "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties").GetRelationship(0).TargetUri.ToString()); // Add some more partB.AddExternalRelationship("http://poi.apache.org/new", "http://example/poi/new"); partB.AddExternalRelationship("http://poi.apache.org/alt", "http://example/poi/alt"); // Check the relations Assert.AreEqual(2, partA.Relationships.Size); Assert.AreEqual(3, partB.Relationships.Size); Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.OriginalString); Assert.AreEqual("http://poi.apache.org/", partA.GetRelationship("rId2").TargetUri.OriginalString); Assert.AreEqual("http://poi.apache.org/ss/", partB.GetRelationship("rId1").TargetUri.OriginalString); Assert.AreEqual("http://poi.apache.org/new", partB.GetRelationship("rId2").TargetUri.OriginalString); Assert.AreEqual("http://poi.apache.org/alt", partB.GetRelationship("rId3").TargetUri.OriginalString); }
public void NonOOXMLFileTypes() { // Spreadsheet has a good mix of alternate file types POIDataSamples files = POIDataSamples.GetSpreadSheetInstance(); // OLE2 - Stream try { Stream stream = files.OpenResourceAsStream("SampleSS.xls"); try { OPCPackage.Open(stream); } finally { stream.Dispose();//.Close(); } Assert.Fail("Shouldn't be able to open OLE2"); } catch (OLE2NotOfficeXmlFileException e) { Assert.IsTrue(e.Message.Contains("The supplied data appears to be in the OLE2 Format")); Assert.IsTrue(e.Message.Contains("You are calling the part of POI that deals with OOXML")); } // OLE2 - File try { OPCPackage.Open(files.GetFile("SampleSS.xls")); Assert.Fail("Shouldn't be able to open OLE2"); } catch (OLE2NotOfficeXmlFileException e) { Assert.IsTrue(e.Message.Contains("The supplied data appears to be in the OLE2 Format")); Assert.IsTrue(e.Message.Contains("You are calling the part of POI that deals with OOXML")); } // Raw XML - Stream try { Stream stream = files.OpenResourceAsStream("SampleSS.xml"); try { OPCPackage.Open(stream); } finally { stream.Dispose();//.Close(); } Assert.Fail("Shouldn't be able to open XML"); } catch (NotOfficeXmlFileException e) { Assert.IsTrue(e.Message.Contains("The supplied data appears to be a raw XML file")); Assert.IsTrue(e.Message.Contains("Formats such as Office 2003 XML")); } // Raw XML - File try { OPCPackage.Open(files.GetFile("SampleSS.xml")); Assert.Fail("Shouldn't be able to open XML"); } catch (NotOfficeXmlFileException e) { Assert.IsTrue(e.Message.Contains("The supplied data appears to be a raw XML file")); Assert.IsTrue(e.Message.Contains("Formats such as Office 2003 XML")); } // ODF / ODS - Stream try { Stream stream = files.OpenResourceAsStream("SampleSS.ods"); try { OPCPackage.Open(stream); } finally { stream.Dispose();//.Close(); } Assert.Fail("Shouldn't be able to open ODS"); } catch (ODFNotOfficeXmlFileException e) { Assert.IsTrue(e.ToString().Contains("The supplied data appears to be in ODF")); Assert.IsTrue(e.ToString().Contains("Formats like these (eg ODS")); } // ODF / ODS - File try { OPCPackage.Open(files.GetFile("SampleSS.ods")); Assert.Fail("Shouldn't be able to open ODS"); } catch (ODFNotOfficeXmlFileException e) { Assert.IsTrue(e.ToString().Contains("The supplied data appears to be in ODF")); Assert.IsTrue(e.ToString().Contains("Formats like these (eg ODS")); } // Plain Text - Stream try { Stream stream = files.OpenResourceAsStream("SampleSS.txt"); try { OPCPackage.Open(stream); } finally { stream.Dispose();//.Close(); } Assert.Fail("Shouldn't be able to open Plain Text"); } catch (NotOfficeXmlFileException e) { Assert.IsTrue(e.Message.Contains("No valid entries or contents found")); Assert.IsTrue(e.Message.Contains("not a valid OOXML")); } // Plain Text - File try { OPCPackage.Open(files.GetFile("SampleSS.txt")); Assert.Fail("Shouldn't be able to open Plain Text"); } catch (UnsupportedFileFormatException) { // Unhelpful low-level error, sorry } }
//[Ignore("add relation Uri #Sheet1!A1")] public void TestCreatePackageWithCoreDocument() { MemoryStream baos = new MemoryStream(); OPCPackage pkg = OPCPackage.Create(baos); // Add a core document PackagePartName corePartName = PackagingUriHelper.CreatePartName("/xl/workbook.xml"); // Create main part relationship pkg.AddRelationship(corePartName, TargetMode.Internal, PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); // Create main document part PackagePart corePart = pkg.CreatePart(corePartName, "application/vnd.Openxmlformats-officedocument.spreadsheetml.sheet.main+xml"); // Put in some dummy content Stream coreOut = corePart.GetOutputStream(); byte[] buffer = Encoding.UTF8.GetBytes("<dummy-xml />"); coreOut.Write(buffer, 0, buffer.Length); coreOut.Close(); // And another bit PackagePartName sheetPartName = PackagingUriHelper.CreatePartName("/xl/worksheets/sheet1.xml"); PackageRelationship rel = corePart.AddRelationship(sheetPartName, TargetMode.Internal, "http://schemas.Openxmlformats.org/officeDocument/2006/relationships/worksheet", "rSheet1"); Assert.IsNotNull(rel); PackagePart part = pkg.CreatePart(sheetPartName, "application/vnd.Openxmlformats-officedocument.spreadsheetml.worksheet+xml"); Assert.IsNotNull(part); // Dummy content again coreOut = corePart.GetOutputStream(); buffer = Encoding.UTF8.GetBytes("<dummy-xml2 />"); coreOut.Write(buffer, 0, buffer.Length); coreOut.Close(); //add a relationship with internal target: "#Sheet1!A1" corePart.AddRelationship(PackagingUriHelper.ToUri("#Sheet1!A1"), TargetMode.Internal, "http://schemas.Openxmlformats.org/officeDocument/2006/relationships/hyperlink", "rId2"); // Check things are as expected PackageRelationshipCollection coreRels = pkg.GetRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); Assert.AreEqual(1, coreRels.Size); PackageRelationship coreRel = coreRels.GetRelationship(0); Assert.IsNotNull(coreRel); Assert.AreEqual("/", coreRel.SourceUri.ToString()); Assert.AreEqual("/xl/workbook.xml", coreRel.TargetUri.ToString()); Assert.IsNotNull(pkg.GetPart(coreRel)); // Save and re-load pkg.Close(); FileInfo tmp = TempFile.CreateTempFile("testCreatePackageWithCoreDocument", ".zip"); FileStream fout = new FileStream(tmp.FullName, FileMode.Create, FileAccess.ReadWrite); try { buffer = baos.ToArray(); fout.Write(buffer, 0, buffer.Length); } finally { fout.Close(); } pkg = OPCPackage.Open(tmp.FullName); //tmp.Delete(); try { // Check still right coreRels = pkg.GetRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); Assert.AreEqual(1, coreRels.Size); coreRel = coreRels.GetRelationship(0); Assert.IsNotNull(coreRel); Assert.AreEqual("/", coreRel.SourceUri.ToString()); Assert.AreEqual("/xl/workbook.xml", coreRel.TargetUri.ToString()); corePart = pkg.GetPart(coreRel); Assert.IsNotNull(corePart); PackageRelationshipCollection rels = corePart.GetRelationshipsByType("http://schemas.Openxmlformats.org/officeDocument/2006/relationships/hyperlink"); Assert.AreEqual(1, rels.Size); rel = rels.GetRelationship(0); Assert.IsNotNull(rel); Assert.Warn(" 'Sheet1!A1' and rel.TargetUri.Fragment should be equal."); //Assert.AreEqual("Sheet1!A1", rel.TargetUri.Fragment); assertMSCompatibility(pkg); } finally { pkg.Close(); } Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files."); }
public void CreateForWriting() { string fileName = TESTFILE_DIR + "testCreate.docx"; if (File.Exists(fileName)) { File.Delete(fileName); } try { using (Stream s = new FileStream(fileName, FileMode.CreateNew)) { List<DefaultInfo> ldi = new List<DefaultInfo>(); ldi.Add(new DefaultInfo("xls", "application/xml")); ldi.Add(new DefaultInfo("rels", "application/vnd.openxmlformats-package.relationships+xml")); using (OPCPackage package = new OPCPackage(s, ldi, OpenXmlFormatDefinition.OpenXmlFormat.Transitional)) { using (Stream str = File.Open(TESTFILE_DIR + "document1.xml", FileMode.Open)) { PartInfo rel = new PartInfo(package); rel.Type = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; rel.Id = "rId1"; rel.Target = "/word/document.xml"; rel.RelatedTo = ""; package.AddContent(rel, str, OpenXmlFormatDefinition.OpenXmlFormat.Transitional); } } } Assert.IsTrue(File.Exists(fileName)); using (OPCPackage readPackage = new OPCPackage(File.Open(fileName, FileMode.Open))) { PartInfo rel = readPackage.GetRelatedObjects("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument")[0]; Stream str = rel.GetContent(); Assert.IsNotNull(str, "whoops, no content found"); DocxTestUtilities.ValidateDocxMainStream(str, TESTFILE_DIR); Assert.AreEqual("word/document.xml", rel.Target); Assert.AreEqual(2, readPackage.GetDefaultTypes().Count, "Expected the written package to containt eh 2 defaults in the original package"); } } finally { File.Delete(fileName); } }
/** * Constructor. * * @param pack * The owner package. * @param partName * The part name. * @param contentType * The content type. * @param loadRelationships * Specify if the relationships will be loaded. * @throws InvalidFormatException * If the specified URI is not OPC compliant. */ public MemoryPackagePart(OPCPackage pack, PackagePartName partName, String contentType, bool loadRelationships) : base(pack, partName, new ContentType(contentType), loadRelationships) { }
/** * Constructor. * * @param targetPackage * Container. * @param partName * Name of the part to unmarshall. */ public UnmarshallContext(OPCPackage targetPackage, PackagePartName partName) { this._package = targetPackage; this.partName = partName; }
public void TestGetRelationshipsToRoot() { using (Stream s = new FileStream(TESTFILE_DIR + "test002.docx", FileMode.Open)) { OPCPackage package = new OPCPackage(s); List<PartInfo> parts = package.GetRelatedObjects(); Assert.AreEqual(4, parts.Count, "expected 2 items with relationships"); } }
public void TestGetContentTypesForPart() { using (Stream s = new FileStream(TESTFILE_DIR + "test002.docx", FileMode.Open)) { OPCPackage package = new OPCPackage(s); List<PartInfo> rels = package.GetRelatedObjects(); Assert.AreEqual(4, rels.Count, "expected four relationships to the root node"); Assert.AreEqual("application/vnd.openxmlformats-officedocument.extended-properties+xml", rels[0].GetContentType()); } }
public void TestGetRelationshipsForObject() { using (Stream s = new FileStream(TESTFILE_DIR + "test002.docx", FileMode.Open)) { OPCPackage package = new OPCPackage(s); List<PartInfo> rels = package.GetRelatedObjects(); Assert.AreEqual(4, rels.Count, "expected four relationships to the root node"); PartInfo rel = rels[0]; Assert.AreEqual("rId3", rel.Id); Assert.AreEqual("http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", rel.Type); Assert.AreEqual("docProps/app.xml", rel.Target); Assert.AreEqual("", rel.RelatedTo); Assert.IsFalse(rel.External); PartInfo piWordDoc = rels[2]; Assert.AreEqual("word/document.xml", piWordDoc.Target); rels = piWordDoc.GetRelatedObjects(); Assert.AreEqual(12, rels.Count); } }
public void TestCreateFromNullStreamThrows() { OPCPackage package = new OPCPackage(null); }
/** * Constructor. * * @param pack * Parent package. * @param partName * The part name, relative to the parent Package root. * @param contentType * The Multipurpose Internet Mail Extensions (MIME) content type * of the part's data stream. */ public PackagePart(OPCPackage pack, PackagePartName partName, String contentType) : this(pack, partName, new ContentType(contentType)) { }
protected POIXMLDocument(OPCPackage pkg) : base(pkg) { this.pkg = pkg; }
/** * Delegate constructor to the super constructor. * * @param in * The input stream to parse to fill internal content type * collections. * @throws InvalidFormatException * If the content types part content is not valid. */ public ZipContentTypeManager(Stream in1, OPCPackage pkg):base(in1, pkg) { }
/** * Constructor. * * @param container * The container package. * @param zipEntry * The zip entry corresponding to this part. * @param partName * The part name. * @param contentType * Content type. * @throws InvalidFormatException * Throws if the content of this part is invalid. */ public ZipPackagePart(OPCPackage container, ZipEntry zipEntry, PackagePartName partName, String contentType) : base(container, partName, contentType) { this.zipEntry = zipEntry; }
/** * @param opcPackage the opc package to be handled by this thread, stored as thread-local */ public void SetOpcPackage(OPCPackage opcPackage) { this.opcPackage.Value = opcPackage; }
public void TestGetRelatedPartById() { using (Stream s = new FileStream(TESTFILE_DIR + "test002.docx", FileMode.Open)) { OPCPackage package = new OPCPackage(s); RelatedPartProvider rpp = new RelatedPartProvider(package, package.RootPart); PartInfo relatedPart = rpp.GetRelationPart("rId1"); Assert.AreEqual("word/document.xml", relatedPart.Target); relatedPart = rpp.GetRelationPart("rId2"); Assert.AreEqual("docProps/core.xml", relatedPart.Target); } }
public override bool Equals(Object obj) { /** * In case two objects ARE Equal, but its not the same instance, this * implementation will always run through the whole * byte-array-comparison before returning true. If this will turn into a * performance issue, two possible approaches are available:<br> * a) Use the Checksum only and take the risk that two images might have * the same CRC32 sum, although they are not the same.<br> * b) Use a second (or third) Checksum algorithm to minimise the chance * that two images have the same Checksums but are not equal (e.g. * CRC32, MD5 and SHA-1 Checksums, Additionally compare the * data-byte-array lengths). */ if (obj == this) { return(true); } if (obj == null) { return(false); } if (!(obj is XWPFPictureData)) { return(false); } XWPFPictureData picData = (XWPFPictureData)obj; PackagePart foreignPackagePart = picData.GetPackagePart(); PackagePart ownPackagePart = this.GetPackagePart(); if ((foreignPackagePart != null && ownPackagePart == null) || (foreignPackagePart == null && ownPackagePart != null)) { return(false); } if (ownPackagePart != null) { OPCPackage foreignPackage = foreignPackagePart.Package; OPCPackage ownPackage = ownPackagePart.Package; if ((foreignPackage != null && ownPackage == null) || (foreignPackage == null && ownPackage != null)) { return(false); } if (ownPackage != null) { if (!ownPackage.Equals(foreignPackage)) { return(false); } } } long foreignChecksum = picData.Checksum; long localChecksum = Checksum; if (!(localChecksum.Equals(foreignChecksum))) { return(false); } return(Arrays.Equals(this.GetData(), picData.GetData())); }
/** * Constructor. */ public PackageRelationshipCollection(OPCPackage container) : this(container, null) { }
/// <summary> /// Creates an XSSFWorkbook from the given OOXML Package /// </summary> public static IWorkbook Create(OPCPackage pkg) { return(new XSSFWorkbook(pkg)); }
public XSSFEventBasedExcelExtractor(String path) : this(OPCPackage.Open(path)) { }
/** * Constructor. * * @param container * The container package. * @param partName * Part name. * @param contentType * Content type. * @throws InvalidFormatException * Throws if the content of this part invalid. */ public ZipPackagePart(OPCPackage container, PackagePartName partName, String contentType) : base(container, partName, contentType) { }
/// <summary> /// Creates the appropriate HSSFWorkbook / XSSFWorkbook from /// the given File, which must exist and be readable. /// </summary> /// <param name="file"></param> /// <param name="password"></param> /// <param name="readOnly"></param> /// <returns></returns> /// <remarks> /// Note that for Workbooks opened this way, it is not possible /// to explicitly close the underlying File resource. /// </remarks> public static IWorkbook Create(Stream inputStream, string password, bool readOnly) { inputStream = new PushbackStream(inputStream); try { if (POIFSFileSystem.HasPOIFSHeader(inputStream)) { if (DocumentFactoryHelper.GetPasswordProtected(inputStream) == DocumentFactoryHelper.OfficeProtectType.ProtectedOOXML) { inputStream.Position = 0; POIFSFileSystem fs = new POIFSFileSystem(inputStream); var decriptedStream = DocumentFactoryHelper.GetDecryptedStream(fs, password); return(new XSSFWorkbook(decriptedStream)); } inputStream.Position = 0; NPOIFSFileSystem nfs = new NPOIFSFileSystem(inputStream); try { return(Create(nfs, password)); } finally { // ensure that the file-handle is closed again if (nfs != null) { nfs.Close(); } } } inputStream.Position = 0; if (DocumentFactoryHelper.HasOOXMLHeader(inputStream)) { inputStream.Position = 0; OPCPackage pkg = OPCPackage.Open(inputStream, readOnly); try { return(new XSSFWorkbook(pkg)); } catch (IOException ioe) { // ensure that file handles are closed (use revert() to not re-write the file) pkg.Revert(); //pkg.close(); // rethrow exception throw ioe; } catch (Exception ioe) { // ensure that file handles are closed (use revert() to not re-write the file) pkg.Revert(); //pkg.close(); // rethrow exception throw ioe; } } } finally { if (inputStream != null) { inputStream.Dispose(); } } throw new InvalidFormatException("Your stream was neither an OLE2 stream, nor an OOXML stream."); }
public void SaveLoadNew() { XSSFWorkbook workbook = new XSSFWorkbook(); //check that the default date system is Set to 1900 CT_WorkbookPr pr = workbook.GetCTWorkbook().workbookPr; Assert.IsNotNull(pr); Assert.IsTrue(pr.IsSetDate1904()); Assert.IsFalse(pr.date1904, "XSSF must use the 1900 date system"); ISheet sheet1 = workbook.CreateSheet("sheet1"); ISheet sheet2 = workbook.CreateSheet("sheet2"); workbook.CreateSheet("sheet3"); IRichTextString rts = workbook.GetCreationHelper().CreateRichTextString("hello world"); sheet1.CreateRow(0).CreateCell((short)0).SetCellValue(1.2); sheet1.CreateRow(1).CreateCell((short)0).SetCellValue(rts); sheet2.CreateRow(0); Assert.AreEqual(0, workbook.GetSheetAt(0).FirstRowNum); Assert.AreEqual(1, workbook.GetSheetAt(0).LastRowNum); Assert.AreEqual(0, workbook.GetSheetAt(1).FirstRowNum); Assert.AreEqual(0, workbook.GetSheetAt(1).LastRowNum); Assert.AreEqual(0, workbook.GetSheetAt(2).FirstRowNum); Assert.AreEqual(0, workbook.GetSheetAt(2).LastRowNum); FileInfo file = TempFile.CreateTempFile("poi-", ".xlsx"); Stream out1 = File.OpenWrite(file.Name); workbook.Write(out1); out1.Close(); // Check the namespace Contains what we'd expect it to OPCPackage pkg = OPCPackage.Open(file.ToString()); PackagePart wbRelPart = pkg.GetPart(PackagingUriHelper.CreatePartName("/xl/_rels/workbook.xml.rels")); Assert.IsNotNull(wbRelPart); Assert.IsTrue(wbRelPart.IsRelationshipPart); Assert.AreEqual(ContentTypes.RELATIONSHIPS_PART, wbRelPart.ContentType); PackagePart wbPart = pkg.GetPart(PackagingUriHelper.CreatePartName("/xl/workbook.xml")); // Links to the three sheets, shared strings and styles Assert.IsTrue(wbPart.HasRelationships); Assert.AreEqual(5, wbPart.Relationships.Size); // Load back the XSSFWorkbook workbook = new XSSFWorkbook(pkg); Assert.AreEqual(3, workbook.NumberOfSheets); Assert.IsNotNull(workbook.GetSheetAt(0)); Assert.IsNotNull(workbook.GetSheetAt(1)); Assert.IsNotNull(workbook.GetSheetAt(2)); Assert.IsNotNull(workbook.GetSharedStringSource()); Assert.IsNotNull(workbook.GetStylesSource()); Assert.AreEqual(0, workbook.GetSheetAt(0).FirstRowNum); Assert.AreEqual(1, workbook.GetSheetAt(0).LastRowNum); Assert.AreEqual(0, workbook.GetSheetAt(1).FirstRowNum); Assert.AreEqual(0, workbook.GetSheetAt(1).LastRowNum); Assert.AreEqual(0, workbook.GetSheetAt(2).FirstRowNum); Assert.AreEqual(0, workbook.GetSheetAt(2).LastRowNum); sheet1 = workbook.GetSheetAt(0); Assert.AreEqual(1.2, sheet1.GetRow(0).GetCell(0).NumericCellValue, 0.0001); Assert.AreEqual("hello world", sheet1.GetRow(1).GetCell(0).RichStringCellValue.String); pkg.Close(); }
/** * Constructor. * * @param pack * The owner package. * @param partName * The part name. * @param contentType * The content type. * @throws InvalidFormatException * If the specified URI is not OPC compliant. */ public MemoryPackagePart(OPCPackage pack, PackagePartName partName, String contentType) : base(pack, partName, contentType) { }
public void TestOpenPackage() { FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestOpenPackageTMP.docx"); FileInfo inputFile = OpenXml4NetTestDataSamples.GetSampleFile("TestOpenPackageINPUT.docx"); FileInfo expectedFile = OpenXml4NetTestDataSamples.GetSampleFile("TestOpenPackageOUTPUT.docx"); // Copy the input file in the output directory FileHelper.CopyFile(inputFile.FullName, targetFile.FullName); // Create a namespace OPCPackage pkg = OPCPackage.Open(targetFile.FullName); // Modify core part PackagePartName corePartName = PackagingUriHelper .CreatePartName("/word/document.xml"); PackagePart corePart = pkg.GetPart(corePartName); // Delete some part to have a valid document foreach (PackageRelationship rel in corePart.Relationships) { corePart.RemoveRelationship(rel.Id); pkg.RemovePart(PackagingUriHelper.CreatePartName(PackagingUriHelper .ResolvePartUri(corePart.PartName.URI, rel .TargetUri))); } // Create a content XmlDocument doc = new XmlDocument(); XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable); string wuri = "http://schemas.openxmlformats.org/wordProcessingml/2006/main"; mgr.AddNamespace("w", wuri); XmlElement elDocument = doc.CreateElement("w:document", wuri); doc.AppendChild(elDocument); XmlElement elBody = doc.CreateElement("w:body", wuri); elDocument.AppendChild(elBody); XmlElement elParagraph = doc.CreateElement("w:p", wuri); elBody.AppendChild(elParagraph); XmlElement elRun = doc.CreateElement("w:r", wuri); elParagraph.AppendChild(elRun); XmlElement elText = doc.CreateElement("w:t", wuri); elRun.AppendChild(elText); elText.InnerText = ("Hello Open XML !"); StreamHelper.SaveXmlInStream(doc, corePart.GetOutputStream()); // Save and close try { pkg.Close(); } catch (IOException) { Assert.Fail(); } ZipFileAssert.AssertEqual(expectedFile, targetFile); File.Delete(targetFile.FullName); Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files."); }
public void TestCreateExcelHyperlinkRelations() { string filepath = OpenXml4NetTestDataSamples.GetSampleFileName("ExcelWithHyperlinks.xlsx"); OPCPackage pkg = OPCPackage.Open(filepath, PackageAccess.READ_WRITE); PackagePart sheet = pkg.GetPart( PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS)); Assert.IsNotNull(sheet); Assert.AreEqual(3, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size); // Add three new ones PackageRelationship openxml4j = sheet.AddExternalRelationship("http://www.Openxml4j.org/", HYPERLINK_REL_TYPE); PackageRelationship sf = sheet.AddExternalRelationship("http://openxml4j.sf.net/", HYPERLINK_REL_TYPE); PackageRelationship file = sheet.AddExternalRelationship("MyDocument.docx", HYPERLINK_REL_TYPE); // Check they were Added properly Assert.IsNotNull(openxml4j); Assert.IsNotNull(sf); Assert.IsNotNull(file); Assert.AreEqual(6, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size); Assert.AreEqual("http://www.openxml4j.org/", openxml4j.TargetUri.ToString()); Assert.AreEqual("/xl/worksheets/sheet1.xml", openxml4j.SourceUri.ToString()); Assert.AreEqual(HYPERLINK_REL_TYPE, openxml4j.RelationshipType); Assert.AreEqual("http://openxml4j.sf.net/", sf.TargetUri.ToString()); Assert.AreEqual("/xl/worksheets/sheet1.xml", sf.SourceUri.ToString()); Assert.AreEqual(HYPERLINK_REL_TYPE, sf.RelationshipType); Assert.AreEqual("MyDocument.docx", file.TargetUri.ToString()); Assert.AreEqual("/xl/worksheets/sheet1.xml", file.SourceUri.ToString()); Assert.AreEqual(HYPERLINK_REL_TYPE, file.RelationshipType); // Will Get ids 7, 8 and 9, as we already have 1-6 Assert.AreEqual("rId7", openxml4j.Id); Assert.AreEqual("rId8", sf.Id); Assert.AreEqual("rId9", file.Id); // Write out and re-load MemoryStream baos = new MemoryStream(); pkg.Save(baos); MemoryStream bais = new MemoryStream(baos.ToArray()); pkg = OPCPackage.Open(bais); // use revert to not re-write the input file pkg.Revert(); // Check again sheet = pkg.GetPart( PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS)); Assert.AreEqual(6, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size); Assert.AreEqual("http://poi.apache.org/", sheet.GetRelationship("rId1").TargetUri.ToString()); Assert.AreEqual("mailto:[email protected]?subject=XSSF Hyperlinks", sheet.GetRelationship("rId3").TargetUri.ToString()); Assert.AreEqual("http://www.openxml4j.org/", sheet.GetRelationship("rId7").TargetUri.ToString()); Assert.AreEqual("http://openxml4j.sf.net/", sheet.GetRelationship("rId8").TargetUri.ToString()); Assert.AreEqual("MyDocument.docx", sheet.GetRelationship("rId9").TargetUri.ToString()); }
public static OPCPackage OpenSamplePackage(String sampleName) { return(OPCPackage.Open( HSSFTestDataSamples.OpenSampleFileStream(sampleName) )); }
protected void AddManifestReferences(List <Reference> manifestReferences) { OPCPackage ooxml = signatureConfig.GetOpcPackage(); List <PackagePart> relsEntryNames = ooxml.GetPartsByContentType(ContentTypes.RELATIONSHIPS_PART); HashSet <String> digestedPartNames = new HashSet <String>(); //foreach (PackagePart pp in relsEntryNames) //{ // String baseUri = pp.PartName.Name.ReplaceFirst("(.*)/_rels/.*", "$1"); // PackageRelationshipCollection prc; // try // { // prc = new PackageRelationshipCollection(ooxml); // prc.ParseRelationshipsPart(pp); // } // catch (InvalidFormatException e) // { // throw new XMLSignatureException("Invalid relationship descriptor: " + pp.PartName.Name, e); // } // RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec(); // foreach (PackageRelationship relationship in prc) // { // String relationshipType = relationship.RelationshipType; // /* // * ECMA-376 Part 2 - 3rd edition // * 13.2.4.16 Manifest Element // * "The producer shall not create a Manifest element that references any data outside of the package." // */ // if (TargetMode.EXTERNAL == relationship.TargetMode) // { // continue; // } // if (!isSignedRelationship(relationshipType)) continue; // parameterSpec.AddRelationshipReference(relationship.Id); // // TODO: find a better way ... // String partName = baseUri + relationship.TargetURI.ToString(); // try // { // partName = new URI(partName).normalize().Path.Replace('\\', '/'); // LOG.Log(POILogger.DEBUG, "part name: " + partName); // } // catch (URISyntaxException e) // { // throw new XMLSignatureException(e); // } // String contentType; // try // { // PackagePartName relName = PackagingURIHelper.CreatePartName(partName); // PackagePart pp2 = ooxml.GetPart(relName); // contentType = pp2.ContentType; // } // catch (InvalidFormatException e) // { // throw new XMLSignatureException(e); // } // if (relationshipType.EndsWith("customXml") // && !(contentType.Equals("inkml+xml") || contentType.Equals("text/xml"))) // { // LOG.Log(POILogger.DEBUG, "skipping customXml with content type: " + contentType); // continue; // } // if (!digestedPartNames.Contains(partName)) // { // // We only digest a part once. // String uri = partName + "?ContentType=" + contentType; // Reference reference = newReference(uri, null, null, null, null); // manifestReferences.Add(reference); // digestedPartNames.Add(partName); // } // } // if (parameterSpec.HasSourceIds()) // { // List<Transform> transforms = new List<Transform>(); // transforms.Add(newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec)); // transforms.Add(newTransform(CanonicalizationMethod.INCLUSIVE)); // String uri = pp.PartName.Name // + "?ContentType=application/vnd.Openxmlformats-package.relationships+xml"; // Reference reference = newReference(uri, transforms, null, null, null); // manifestReferences.Add(reference); // } //} throw new NotImplementedException(); }
public XSSFWorkbook(OPCPackage pkg) : base(pkg) { this.Load((POIXMLFactory)XSSFFactory.GetInstance()); }
/** * Construct POIXMLDocumentPart representing a "core document" namespace part. */ public POIXMLDocumentPart(OPCPackage pkg) : this(pkg, PackageRelationshipTypes.CORE_DOCUMENT) { }
private void ValidateFileRecursively(string outputFile, PartProcessingDelegate whatToDo) { using (OPCPackage package = new OPCPackage(File.Open(outputFile, FileMode.Open))) { DoSomethingToContentPartsRecursively(package, package.RootPart, whatToDo); } }
public XWPFWordExtractor(OPCPackage Container) : this(new XWPFDocument(Container)) { }
private void DoSomethingToContentPartsRecursively(OPCPackage package, PartInfo part, PartProcessingDelegate whatToDo) { using (Stream data = part.GetContent()) { whatToDo(data, part); } foreach (PartInfo pi in part.GetRelatedObjects()) { DoSomethingToContentPartsRecursively(package, pi, whatToDo); } }
/** * Constructor. * * @param pack * Parent package. * @param partName * The part name, relative to the parent Package root. * @param contentType * The content type. * @throws InvalidFormatException * If the specified URI is not valid. */ protected PackagePart(OPCPackage pack, PackagePartName partName, ContentType contentType) : this(pack, partName, contentType, true) { }
public void TestSetProperties() { String inputPath = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageCoreProperiesSetters.docx"); FileInfo outputFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx"); // Open namespace OPCPackage p = OPCPackage.Open(inputPath, PackageAccess.READ_WRITE); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); DateTime dateToInsert = DateTime.Parse("2007-05-12T08:00:00Z").ToUniversalTime(); SimpleDateFormat msdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //msdf.TimeZone = (LocaleUtil.TIMEZONE_UTC); PackageProperties props = p.GetPackageProperties(); //test various date formats props.SetCreatedProperty("2007-05-12T08:00:00Z"); Assert.AreEqual(dateToInsert, props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T08:00:00"); //no Z, assume Z Assert.AreEqual(dateToInsert, props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T08:00:00.123Z");//millis Assert.AreEqual(msdf.Parse("2007-05-12T08:00:00.123Z"), props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T10:00:00+0200"); Assert.AreEqual(dateToInsert, props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T10:00:00+02:00");//colon in tz Assert.AreEqual(dateToInsert, props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T06:00:00-0200"); Assert.AreEqual(dateToInsert, props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T10:00:00.123+0200"); Assert.AreEqual(msdf.Parse("2007-05-12T08:00:00.123Z"), props.GetCreatedProperty().Value); props.SetCategoryProperty("MyCategory"); props.SetCategoryProperty("MyCategory"); props.SetContentStatusProperty("MyContentStatus"); props.SetContentTypeProperty("MyContentType"); //props.SetCreatedProperty(new DateTime?(dateToInsert)); props.SetCreatorProperty("MyCreator"); props.SetDescriptionProperty("MyDescription"); props.SetIdentifierProperty("MyIdentifier"); props.SetKeywordsProperty("MyKeywords"); props.SetLanguageProperty("MyLanguage"); props.SetLastModifiedByProperty("Julien Chable"); props.SetLastPrintedProperty(new Nullable <DateTime>(dateToInsert)); props.SetModifiedProperty(new Nullable <DateTime>(dateToInsert)); props.SetRevisionProperty("2"); props.SetTitleProperty("MyTitle"); props.SetSubjectProperty("MySubject"); props.SetVersionProperty("2"); p.Revert(); // Open the newly Created file to check core properties saved values. OPCPackage p2 = OPCPackage.Open(outputFile.Name, PackageAccess.READ); CompareProperties(p2); p2.Revert(); outputFile.Delete(); }
public void TestFileWithContentTypeParams() { Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("ContentTypeHasParameters.ooxml"); OPCPackage p = OPCPackage.Open(is1); String typeResqml = "application/x-resqml+xml"; // Check the types on everything foreach (PackagePart part in p.GetParts()) { // _rels type doesn't have any params if (part.IsRelationshipPart) { Assert.AreEqual(ContentTypes.RELATIONSHIPS_PART, part.ContentType); Assert.AreEqual(ContentTypes.RELATIONSHIPS_PART, part.ContentTypeDetails.ToString()); Assert.AreEqual(false, part.ContentTypeDetails.HasParameters()); Assert.AreEqual(0, part.ContentTypeDetails.GetParameterKeys().Length); } // Core type doesn't have any params else if (part.PartName.ToString().Equals("/docProps/core.xml")) { Assert.AreEqual(ContentTypes.CORE_PROPERTIES_PART, part.ContentType); Assert.AreEqual(ContentTypes.CORE_PROPERTIES_PART, part.ContentTypeDetails.ToString()); Assert.AreEqual(false, part.ContentTypeDetails.HasParameters()); Assert.AreEqual(0, part.ContentTypeDetails.GetParameterKeys().Length); } // Global Crs types do have params else if (part.PartName.ToString().Equals("/global1dCrs.xml")) { Assert.AreEqual(typeResqml, part.ContentType.Substring(0, typeResqml.Length)); Assert.AreEqual(typeResqml, part.ContentTypeDetails.ToString(false)); Assert.AreEqual(true, part.ContentTypeDetails.HasParameters()); Assert.AreEqual(typeResqml + ";version=2.0;type=obj_global1dCrs", part.ContentTypeDetails.ToString()); Assert.AreEqual(2, part.ContentTypeDetails.GetParameterKeys().Length); Assert.AreEqual("2.0", part.ContentTypeDetails.GetParameter("version")); Assert.AreEqual("obj_global1dCrs", part.ContentTypeDetails.GetParameter("type")); } else if (part.PartName.ToString().Equals("/global2dCrs.xml")) { Assert.AreEqual(typeResqml, part.ContentType.Substring(0, typeResqml.Length)); Assert.AreEqual(typeResqml, part.ContentTypeDetails.ToString(false)); Assert.AreEqual(true, part.ContentTypeDetails.HasParameters()); Assert.AreEqual(typeResqml + ";version=2.0;type=obj_global2dCrs", part.ContentTypeDetails.ToString()); Assert.AreEqual(2, part.ContentTypeDetails.GetParameterKeys().Length); Assert.AreEqual("2.0", part.ContentTypeDetails.GetParameter("version")); Assert.AreEqual("obj_global2dCrs", part.ContentTypeDetails.GetParameter("type")); } // Other thingy else if (part.PartName.ToString().Equals("/myTestingGuid.xml")) { Assert.AreEqual(typeResqml, part.ContentType.Substring(0, typeResqml.Length)); Assert.AreEqual(typeResqml, part.ContentTypeDetails.ToString(false)); Assert.AreEqual(true, part.ContentTypeDetails.HasParameters()); Assert.AreEqual(typeResqml + ";version=2.0;type=obj_tectonicBoundaryFeature", part.ContentTypeDetails.ToString()); Assert.AreEqual(2, part.ContentTypeDetails.GetParameterKeys().Length); Assert.AreEqual("2.0", part.ContentTypeDetails.GetParameter("version")); Assert.AreEqual("obj_tectonicBoundaryFeature", part.ContentTypeDetails.GetParameter("type")); } // That should be it! else { Assert.Fail("Unexpected part " + part); } } }
public void TestNoContentTypeForExternalRels() { string sCopyFile = TESTFILE_DIR + "copy.docx"; if (File.Exists(sCopyFile)) File.Delete(sCopyFile); try { using (Stream str = File.Open(TESTFILE_DIR + "test002.docx", FileMode.Open)) { using (DocumentProcessor dp = new DocumentProcessor(str)) { using (dp.Output = File.Open(sCopyFile, FileMode.CreateNew)) { dp.Process(DocumentProcessingActions.PassThrough); } } } using (OPCPackage package = new OPCPackage(File.Open(sCopyFile, FileMode.Open))) { List<ContentTypeInfo> ctilist = package.GetContentTypes(); foreach (ContentTypeInfo cti in ctilist) { Assert.IsFalse(cti.Name.StartsWith("file://")); Assert.IsFalse(cti.Name.StartsWith("http://")); } } } finally { File.Delete(sCopyFile); } }
public void TestOpensProperly() { OPCPackage.Open(HSSFTestDataSamples.OpenSampleFileStream("sample.xlsx")); }
public void TestGetPartContent() { using (Stream s = new FileStream(TESTFILE_DIR + "test002.docx", FileMode.Open)) { OPCPackage package = new OPCPackage(s); List<PartInfo> items = package.GetRelatedObjects("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"); Assert.AreEqual(1, items.Count); using (Stream str = items[0].GetContent()) { DocxTestUtilities.ValidateDocxMainStream(str, TESTFILE_DIR); } items = items[0].GetRelatedObjects("http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"); Assert.AreEqual(1, items.Count); using (Stream str2 = items[0].GetContent()) { Assert.IsNotNull(str2); } } }