/// <summary>
        /// Получить ближайшего родительской части документа типа <typeparamref name="T"/>
        /// </summary>
        /// <typeparam name="T">Тип искомого родителя</typeparam>
        /// <param name="part">Часть документа, предка котого требуется найти</param>
        /// <returns>Ближайший предок типа <typeparamref name="T"/></returns>
        public static T ParentPartOfType <T>(this OpenXmlPart part) where T : OpenXmlPart
        {
            var parentParts = part.GetParentParts();

            if (parentParts == null || parentParts.Count() == 0)
            {
                return(null);
            }
            foreach (var p in parentParts)
            {
                if (p == null)
                {
                    continue;
                }
                if (!(p is T))
                {
                    var p2 = p.ParentPartOfType <T>();
                    if (p2 == null)
                    {
                        continue;
                    }
                    return(p2);
                }
                return(p as T);
            }
            return(null);
        }
Esempio n. 2
0
        private static void CopyPartRecursive(OpenXmlPart destinationParent, OpenXmlPart part, string id, IDictionary <OpenXmlPart, OpenXmlPart> mapping)
        {
            if (part is IFixedContentTypePart)
            {
                OpenXmlPart parent = part.GetParentParts().Select(p => mapping.TryGetValue(p, out OpenXmlPart mappedParent) ? mappedParent : null).FirstOrDefault(p => p != null);

                if (mapping.TryGetValue(part, out OpenXmlPart existingPart))
                {
                    destinationParent.CreateRelationshipToPart(existingPart);
                }
                else
                {
                    MethodInfo  method  = typeof(OpenXmlPart).GetTypeInfo().GetMethod(nameof(OpenXmlPart.AddNewPart), new Type[] { typeof(string) }).MakeGenericMethod(part.GetType());
                    OpenXmlPart newPart = method.Invoke(parent, new object[] { id }) as OpenXmlPart;
                    mapping.Add(part, newPart);

                    using (Stream data = part.GetStream())
                    {
                        newPart.FeedData(data);
                    }

                    foreach (IdPartPair relationship in part.Parts)
                    {
                        CopyPartRecursive(newPart, relationship.OpenXmlPart, relationship.RelationshipId, mapping);
                    }
                }
            }
        }
Esempio n. 3
0
        public static void RemovePart(this OpenXmlPart part)
        {
            var parentParts = part.GetParentParts().ToList();

            foreach (var parentPart in parentParts)
            {
                parentPart.DeletePart(part);
            }
        }