CreateRelationship() public méthode

public CreateRelationship ( Uri targetUri, TargetMode targetMode, string relationshipType ) : PackageRelationship
targetUri Uri
targetMode TargetMode
relationshipType string
Résultat PackageRelationship
Exemple #1
0
        /// <summary>
        /// Creates a package-level or part-level relationship and its target part
        /// (if the target part wasn't already created before). If the sourceTargetFilePath does not exist,
        /// then both relationship and part will not be created.
        /// </summary>
        /// <param name="package"></param>
        /// <param name="sourcePart">Set to null for a package-level relationship</param>
        /// <param name="sourceTargetFilePath"></param>
        /// <param name="targetUri"></param>
        /// <param name="targetMimeType"></param>
        /// <param name="relationshipTypeUri"></param>
        /// <param name="targetPart">The target part that was created</param>
        /// <returns>True if relationship and part (if not already created before) was created,
        /// False if source file does not exist and thus relationship and part wasn't created.</returns>
        private static bool CreateRelationshipAndTargetPart(
            System.IO.Packaging.Package package, System.IO.Packaging.PackagePart sourcePart,
            string sourceTargetFilePath, string targetUri, string targetMimeType, string relationshipTypeUri,
            out System.IO.Packaging.PackagePart targetPart)
        {
            // TODO add console output for added parts and relationships

            targetPart = null;

            if (!File.Exists(sourceTargetFilePath))
            {
                Console.WriteLine(
                    "Warning: The following source file does not exist: " + sourceTargetFilePath +
                    ". Part and relationship will not be created.");
                return(false);
            }
            try
            {
                targetPart = package.CreatePart(
                    PackUriHelper.CreatePartUri(
                        new Uri(targetUri, UriKind.Relative)), targetMimeType, CompressionOption.Maximum);
                using (FileStream fileStream = new FileStream(sourceTargetFilePath, FileMode.Open, FileAccess.Read))
                {
                    fileStream.CopyTo(targetPart.GetStream());
                }
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine(
                    "Warning: The following part URI already exists and will not be created again: " +
                    targetUri + ". Relationship will still be created.");
            }
            if (sourcePart == null)
            {
                package.CreateRelationship(
                    PackUriHelper.CreatePartUri(
                        new Uri(targetUri, UriKind.Relative)), TargetMode.Internal, relationshipTypeUri);
            }
            else
            {
                sourcePart.CreateRelationship(
                    PackUriHelper.CreatePartUri(
                        new Uri(targetUri, UriKind.Relative)), TargetMode.Internal, relationshipTypeUri);
            }
            return(true);
        }
 private static void CreatePartRelationship(Uri partUri, string partRelationshipType, string partId, PackagePart parentPart)
 {
     Uri relativeUri = PackUriHelper.GetRelativeUri(parentPart.Uri, partUri);
     parentPart.CreateRelationship(relativeUri, TargetMode.Internal, partRelationshipType, partId);
 }
        private XElement WriteWorkSheet_hyperLinks(WorkSheet sheet, List<Cell> sheetHyperLink, PackagePart worksheetPart)
        {
            XElement sheethyperlinks = new XElement(XName.Get("hyperlinks", ExcelCommon.Schema_WorkBook_Main.NamespaceName));

            Dictionary<string, string> hyps = new Dictionary<string, string>();

            foreach (Cell celllink in sheetHyperLink)
            {
                XElement hyperlinkNode = new XElement(XName.Get("hyperlink", ExcelCommon.Schema_WorkBook_Main.NamespaceName));

                #region "location"
                //if (string.IsNullOrEmpty(celllink._Hyperlink.AbsoluteUri))
                if (celllink._Hyperlink.AbsoluteUri == "xl://internal/")
                {
                    if (celllink._Hyperlink is ExcelHyperLink)
                    {
                        ExcelHyperLink hyperlink = celllink._Hyperlink as ExcelHyperLink;

                        string address = Range.Parse(sheet, celllink.Column.Index, celllink.Row.Index, hyperlink.ColSpann + celllink.Column.Index, celllink.Row.Index + hyperlink.RowSpann).ToAddress();
                        hyperlinkNode.Add(new XAttribute("ref", address));

                        if (hyperlink.ReferenceAddress.IsNotEmpty())
                        {
                            string strlocation = hyperlink.ReferenceAddress;
                            if (strlocation.Contains("!"))
                            {
                                if (strlocation[0] != '\'')
                                {
                                    hyperlinkNode.Add(new XAttribute("location", string.Format("'{0}'!{1}", strlocation.Substring(0, strlocation.IndexOf('!')), strlocation.Substring(strlocation.IndexOf('!') + 1))));
                                }
                                else
                                {
                                    hyperlinkNode.Add(new XAttribute("location", strlocation));
                                }
                            }
                            else
                            {
                                hyperlinkNode.Add(new XAttribute("location", string.Format("'{0}'!{1}", sheet.Name, strlocation)));
                            }
                        }

                        if (hyperlink.Display.IsNotEmpty())
                        {
                            hyperlinkNode.Add(new XAttribute("display", hyperlink.Display));
                        }

                        if (hyperlink.ToolTip.IsNotEmpty())
                        {
                            hyperlinkNode.Add(new XAttribute("tooltip", hyperlink.Display));
                        }
                    }
                }
                else
                {
                    if (hyperlinkNode.Attribute(XName.Get("ref", ExcelCommon.Schema_WorkBook_Main.NamespaceName)) == null)
                    {
                        hyperlinkNode.Add(new XAttribute("ref", celllink.ToString()));
                    }
                    string idRelations = string.Empty;
                    if (hyps.ContainsKey(celllink._Hyperlink.AbsoluteUri))
                    {
                        idRelations = hyps[celllink._Hyperlink.AbsoluteUri];
                    }
                    else
                    {
                        idRelations = worksheetPart.CreateRelationship(celllink._Hyperlink, TargetMode.External, ExcelCommon.Schema_Hyperlink).Id;
                        hyps.Add(celllink._Hyperlink.AbsoluteUri, idRelations);
                    }
                    hyperlinkNode.Add(new XAttribute(XName.Get("id", ExcelCommon.Schema_Relationships), idRelations));
                }
                #endregion
                sheethyperlinks.Add(hyperlinkNode);
            }
            return sheethyperlinks;
        }
        /// <summary>
        /// FileName:workbook.xml 
        /// <para>NodePath:workbook/sheets</para>
        /// </summary>
        private XElement WriteWorkBook_sheets(PackagePart partWorkbook)
        {
            XElement sheets = new XElement(ExcelCommon.Schema_WorkBook_Main + "sheets");

            int sheetID = 1;
            foreach (WorkSheet sheet in this.Workbook.Sheets)
            {
                foreach (var definedName in sheet.Names)
                {
                    this.Context.DefinedNames.Add(definedName);
                }

                XElement sheetElement = new XElement(ExcelCommon.Schema_WorkBook_Main + "sheet");
                sheetElement.Add(new XAttribute("name", sheet.Name));
                sheetElement.Add(new XAttribute("sheetId", sheetID));

                sheet.SheetUri = new Uri("/xl/worksheets/sheet" + sheetID + ".xml", UriKind.Relative);
                sheet.RelationshipID = partWorkbook.CreateRelationship(PackUriHelper.GetRelativeUri(ExcelCommon.Uri_Workbook,
                    sheet.SheetUri), TargetMode.Internal, ExcelCommon.Schema_Relationships + "/worksheet").Id;

                XName name = XName.Get("id", ExcelCommon.Schema_Relationships);
                sheetElement.Add(new XAttribute(name, sheet.RelationshipID));

                #region "Hidden"
                if (sheet.Hidden == ExcelWorksheetHidden.Hidden)
                {
                    sheetElement.Add(new XAttribute("state", "hidden"));
                }
                else if (sheet.Hidden == ExcelWorksheetHidden.VeryHidden)
                {
                    sheetElement.Add(new XAttribute("state", "veryHidden"));
                }
                #endregion

                sheets.Add(sheetElement);
                sheetID++;
            }

            return sheets;
        }
 private void WriteWorkSheet_HeaderFooter_Pictures(WorkSheet sheet, PackagePart worksheetPart)
 {
     if (sheet._HeaderFooter._Pictures != null)
     {
         if (sheet._HeaderFooter._Pictures.Count > 0)
         {
             sheet._HeaderFooter._Pictures.PictureUri = this.Context.Package.GetNewUri(@"/xl/drawings/vmlDrawing{0}.vml");
             PackageRelationship rel = worksheetPart.CreateRelationship(PackUriHelper.GetRelativeUri(sheet.SheetUri, sheet._HeaderFooter._Pictures.PictureUri), TargetMode.Internal, ExcelCommon.Schema_Relationships + "/vmlDrawing");
             sheet._HeaderFooter._Pictures.RelationshipID = rel.Id;
             ((IPersistable)sheet._HeaderFooter._Pictures).Save(this.Context);
         }
         else
         {
             sheet._HeaderFooter._Pictures.RelationshipID = string.Empty;
         }
     }
 }
        private XElement WriteWrokSheetDrawing_Content_pic(ExcelPicture pic, DrawingCollection drawingCollection, PackagePart wrokSheetDrawingPart, int index)
        {
            XElement picNode = new XElement(XName.Get("pic", ExcelCommon.Schema_SheetDrawings));

            #region "nvPicPr"
            XElement nvPicPrNode = new XElement(XName.Get("nvPicPr", ExcelCommon.Schema_SheetDrawings));
            XElement cNvPrNode = new XElement(XName.Get("cNvPr", ExcelCommon.Schema_SheetDrawings),
                new XAttribute(XName.Get("id"), (index + 2).ToString()));
            if (string.IsNullOrEmpty(pic.Name))
                cNvPrNode.Add(new XAttribute(XName.Get("name"), string.Format("图片 {0}", index)));
            else
                cNvPrNode.Add(new XAttribute(XName.Get("name"), pic.Name));

            nvPicPrNode.Add(cNvPrNode);

            XElement cNvPicPrNode = new XElement(XName.Get("cNvPicPr", ExcelCommon.Schema_SheetDrawings));
            cNvPicPrNode.Add(new XElement(XName.Get("picLocks", ExcelCommon.Schema_Drawings), new XAttribute("noChangeAspect", 1)));
            nvPicPrNode.Add(cNvPicPrNode);
            picNode.Add(nvPicPrNode);
            #endregion "nvPicPr"

            #region "blipFill"
            XElement blipFillNode = new XElement(XName.Get("blipFill", ExcelCommon.Schema_SheetDrawings));
            XElement blipNode = new XElement(XName.Get("blip", ExcelCommon.Schema_Drawings));
            blipNode.Add(new XAttribute(XName.Get("R", XNamespace.Xmlns.NamespaceName), ExcelCommon.Schema_Relationships));

            ExcelImageInfo currentImage = SavePicture(pic.Name, pic.ImageFormat, pic.Image, pic.ContentType);
            if (this.Context.HashImageRelationships.ContainsKey(currentImage.Hash))
                blipNode.Add(new XAttribute(XName.Get("embed", ExcelCommon.Schema_Relationships), this.Context.HashImageRelationships[currentImage.Hash]));
            else
            {
                PackageRelationship picRelation = wrokSheetDrawingPart.CreateRelationship(PackUriHelper.GetRelativeUri(drawingCollection.DrawingUri, currentImage.Uri), TargetMode.Internal, ExcelCommon.Schema_Relationships + "/image");
                blipNode.Add(new XAttribute(XName.Get("embed", ExcelCommon.Schema_Relationships), picRelation.Id));
                this.Context.HashImageRelationships.Add(currentImage.Hash, picRelation.Id);
            }
            blipNode.Add(new XAttribute(XName.Get("cstate"), "print"));
            blipFillNode.Add(blipNode);

            XElement stretchNode = new XElement(XName.Get("stretch", ExcelCommon.Schema_Drawings),
                   new XElement(XName.Get("fillRect", ExcelCommon.Schema_Drawings)));
            blipFillNode.Add(stretchNode);
            picNode.Add(blipFillNode);
            #endregion

            #region "spPr"
            XElement spPrNode = new XElement(XName.Get("spPr", ExcelCommon.Schema_SheetDrawings),
                new XElement(XName.Get("xfrm", ExcelCommon.Schema_Drawings),
                    new XElement(XName.Get("off", ExcelCommon.Schema_Drawings),
                        new XAttribute("x", 0), new XAttribute("y", 0)),
                    new XElement(XName.Get("ext", ExcelCommon.Schema_Drawings),
                        new XAttribute("cx", 0), new XAttribute("cy", 0))),
                new XElement(XName.Get("prstGeom", ExcelCommon.Schema_Drawings),
                    new XAttribute("prst", "rect"),
                    new XElement(XName.Get("avLst", ExcelCommon.Schema_Drawings))));
            if (pic._Fill != null)
                WriteWrokSheetDrawing_pic_solidFill(pic._Fill, spPrNode);

            if (pic._Border != null)
                WriteWrokSheetDrawing_pic_ln(pic._Border, spPrNode);

            picNode.Add(spPrNode);
            #endregion

            return picNode;
        }
        private string CreateChartPackage(ExcelChart excelchart, PackagePart wrokSheetDrawingPart, Uri drawingUri)
        {
            Uri uriChart = this.Context.Package.GetNewUri("/xl/charts/chart{0}.xml");
            PackageRelationship chartRelation = wrokSheetDrawingPart.CreateRelationship(PackUriHelper.GetRelativeUri(drawingUri, uriChart), TargetMode.Internal, ExcelCommon.Schema_Relationships + "/chart");
            PackagePart chartPackagePart = this.Context.Package.CreatePart(uriChart, ExcelCommon.ContentType_sheetChart, CompressionOption.NotCompressed);

            XDocument chartDoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
            WriteWrokSheetChart(excelchart, chartDoc);
            using (Stream chartStream = chartPackagePart.GetStream(FileMode.Create, FileAccess.Write))
            {
                chartDoc.Save(chartStream);
                chartStream.Flush();
            }
            return chartRelation.Id;
        }
        private void CreateImagePart(PackagePart sourcePart, BitmapSource imageSource, string imageContentType, int imageIndex)
        {
            // Generate a new unique image part name
            string imagePartUriString = GetImageName(imageIndex, imageContentType);

            // Define an image part uri
            Uri imagePartUri = new Uri(XamlPayloadDirectory + imagePartUriString, UriKind.Relative);

            // Create a part for the image
            PackagePart imagePart = _package.CreatePart(imagePartUri, imageContentType, CompressionOption.NotCompressed);

            // Create the relationship referring from the enrty part to the image part
            PackageRelationship componentRelationship = sourcePart.CreateRelationship(imagePartUri, TargetMode.Internal, XamlRelationshipFromXamlPartToComponentPart);

            // Encode the image data
            BitmapEncoder bitmapEncoder = GetBitmapEncoder(imageContentType);
            bitmapEncoder.Frames.Add(BitmapFrame.Create(imageSource));

            // Save encoded image data into the image part in the package
            Stream imageStream = imagePart.GetStream();
            using (imageStream)
            {
                bitmapEncoder.Save(imageStream);
            }
        }
Exemple #9
0
        /* S T M  C R E A T E  P A R T */
        /*----------------------------------------------------------------------------
            %%Function: StmCreatePart
            %%Qualified: ArbWeb.OOXML.StmCreatePart
            %%Contact: rlittle

        ----------------------------------------------------------------------------*/
        public static Stream StmCreatePart(Package pkg, string sUri, string sContentType, out PackagePart prt)
        {
            Uri uriTeams = new System.Uri(sUri, UriKind.Relative);

            prt = pkg.GetPart(uriTeams);

            List<PackageRelationship> plrel = new List<PackageRelationship>();

            foreach (PackageRelationship rel in prt.GetRelationships())
                {
                plrel.Add(rel);
                }

            prt = null;

            pkg.DeletePart(uriTeams);
            prt = pkg.CreatePart(uriTeams, sContentType);

            foreach (PackageRelationship rel in plrel)
                {
                prt.CreateRelationship(rel.TargetUri, rel.TargetMode, rel.RelationshipType, rel.Id);
                }

            return prt.GetStream(FileMode.Create, FileAccess.Write);
        }