Exemple #1
0
        private static DocumentSettingsPart CreateDocumentSettingsPart(OpenXmlPartContainer mainDocumentPart)
        {
            var part = mainDocumentPart.AddNewPart <DocumentSettingsPart>();

            part.Settings = new Settings();
            return(part);
        }
 /// <summary>
 /// Adds a feature to track eventing for a package lifecycle events.
 /// </summary>
 /// <param name="container">Container to add the feature to.</param>
 public static void AddPartRootEventsFeature(this OpenXmlPartContainer container)
 {
     if (container.Features.Get <IPartRootEventsFeature>() is null)
     {
         container.Features.Set <IPartRootEventsFeature>(new PartRootEventsFeature());
     }
 }
        /// <summary>
        /// Parse the document in order to proceed to the alimentation of all blocks into the given container.
        /// </summary>
        /// <param name="container">Container to build.</param>
        public virtual void ParseDocument(OpenXmlPartContainer container)
        {
            IList <BlockItem> blocks = GetBlocks(container);

            foreach (BlockItem block in blocks)
            {
                BlockConfiguration config = GetBlockConfiguration(block);
                try
                {
                    if (TextBlock.IsMatching(config.Type))
                    {
                        TextBlock.BuildContent(ReportData, container, block, config.Name, config.Options);
                    }
                    else if (TableBlock.IsMatching(config.Type))
                    {
                        TableBlock.BuildContent(ReportData, container, block, config.Name, config.Options);
                    }
                    else if (GraphBlock.IsMatching(config.Type))
                    {
                        GraphBlock.BuildContent(ReportData, Package, block, config.Name, config.Options);
                    }
                    else
                    {
                        LogHelper.Instance.LogWarnFormat("Block type '{0}' not found.", config.Type);
                    }
                }
                catch (Exception exception)
                {
                    string logMessage = $"Exception thrown during document parsing (BlockType : {(null != config ? config.Type : string.Empty)}, BlockName : {(null != config ? config.Name : string.Empty)})";
                    LogHelper.Instance.LogError(logMessage, exception);
                }
            }
        }
Exemple #4
0
        private static void UpdateWordBlock(OpenXmlPartContainer container, OpenXmlElement block, string content)
        {
            OXW.Text new_text = new OXW.Text(content);
            if (!string.IsNullOrEmpty(content) && (char.IsWhiteSpace(content[0]) || char.IsWhiteSpace(content[content.Length - 1])))
            {
                new_text.Space = SpaceProcessingModeValues.Preserve;
            }
            OXW.Run           run             = new OXW.Run(new_text);
            OXW.RunProperties originalRunProp = block.Descendants <OXW.RunProperties>().FirstOrDefault();
            if (originalRunProp != null)
            {
                run.RunProperties = (OXW.RunProperties)originalRunProp.CloneNode(true);
            }
            OpenXmlElement finalBlock  = run;
            var            cbcontainer = block.Parent;

            if (null != cbcontainer)
            {
                cbcontainer.Parent.ReplaceChild(finalBlock, cbcontainer);
            }
            var docPart = container.GetPartsOfType <MainDocumentPart>().FirstOrDefault();

            if (docPart == null)
            {
                var p = container as OpenXmlPart;
                if (p != null)
                {
                    docPart = p.GetParentParts().FirstOrDefault(_ => _ is MainDocumentPart) as MainDocumentPart;
                }
            }
            if (docPart != null)
            {
                docPart.Document.Save();
            }
        }
        public string GetCellValue(OpenXmlPartContainer wbPart, EnumValue <CellValues> dataType, string value)
        {
            if (dataType != null)
            {
                switch (dataType.Value)
                {
                case CellValues.SharedString:
                    var stringTable = wbPart.GetPartsOfType <SharedStringTablePart>().FirstOrDefault();
                    if (stringTable != null)
                    {
                        value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
                    }
                    break;

                case CellValues.Boolean:
                    switch (value)
                    {
                    case "0":
                        value = "False";
                        break;

                    default:
                        value = "True";
                        break;
                    }
                    break;
                }
            }

            return(value);
        }
Exemple #6
0
        /// <summary>
        /// Returns all block contained into the container given in argument.
        /// </summary>
        /// <param name="container">Container where the block items will be found.</param>
        /// <returns>All block contained into the container given in argument.</returns>
        protected override List <BlockItem> GetBlocks(OpenXmlPartContainer container)
        {
            OpenXmlPartRootElement rootContainer = GetRootContainer(container);
            var blocks = rootContainer.Descendants <SdtElement>()
                         .Select(_ => new BlockItem
            {
                OxpBlock  = _,
                XBlock    = XElement.Parse(_.OuterXml),
                Container = container
            })
                         .ToList();
            var addblocks = rootContainer.Descendants <DocProperties>()
                            .Where(_ => null != _.Description &&
                                   _.Description.HasValue &&
                                   !string.IsNullOrWhiteSpace(_.Description.Value) &&
                                   (_.Parent.Parent is Drawing || _.Parent.Parent is Table))
                            .Select(_ => new BlockItem
            {
                OxpBlock  = _.Parent.Parent,
                XBlock    = XElement.Parse(_.Parent.Parent.OuterXml),
                Container = container
            })
                            .ToList();;

            blocks.AddRange(addblocks);
            return(blocks);
        }
        /// <summary>
        /// Returns all block contained into the container given in argument.
        /// </summary>
        /// <param name="container">Container where the block items will be found.</param>
        /// <returns>All block contained into the container given in argument.</returns>
        protected override List <BlockItem> GetBlocks(OpenXmlPartContainer container)
        {
            // TODO : Finalize Excel alimentation


            throw new NotImplementedException();
        }
        public static IEnumerable <OpenXmlPart> AllParts(this OpenXmlPartContainer container)
        {
            var roots  = container.Parts.Select(a => a.OpenXmlPart);
            var result = DirectedGraph <OpenXmlPart> .Generate(roots, c => c.Parts.Select(a => a.OpenXmlPart));

            return(result);
        }
        public string GetCellValue(OpenXmlPartContainer wbPart, EnumValue<CellValues> dataType, string value)
        {
            if (dataType != null)
            {
                switch (dataType.Value)
                {
                    case CellValues.SharedString:
                        var stringTable = wbPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
                        if (stringTable != null)
                        {
                            value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
                        }
                        break;

                    case CellValues.Boolean:
                        switch (value)
                        {
                            case "0":
                                value = "False";
                                break;
                            default:
                                value = "True";
                                break;
                        }
                        break;
                }

            }

            return value;
        }
 public WorkbookPart(OpenXmlPartContainer parent, string contentType)
     : base(parent, 0)
 {
     this._worksheetNumber    = 1;
     this._chartsheetNumber   = 1;
     this._externalLinkNumber = 1;
     this._type = contentType;
 }
Exemple #11
0
 public static void ApplyContent(ReportData client, OpenXmlPartContainer container, BlockItem block, TableDefinition content, Dictionary<string, string> options)
 {
     var contentblock = GetTableContentBlock(client, block);
     if (null != contentblock)
     {
         UpdateBlock(client, container, contentblock, content, options);
     }
 }
 /// <summary>
 /// Check if current <paramref name="part"/> is main part of the package.
 /// </summary>
 /// <param name="part">Current Part</param>
 /// <returns>Return true if <paramref name="part"/> is main part of the package.</returns>
 public static bool IsMainPart(this OpenXmlPartContainer part)
 {
     if (part is MainDocumentPart || part is WorkbookPart || part is PresentationPart)
     {
         return(true);
     }
     return(false);
 }
        public ExcelSheetValue ParseCell(OpenXmlPartContainer wbPart, Cell cell)
        {
            var coords = _cellCoordinateParser.ParseCoordinates(cell.CellReference);
            var value = _cellValueParser.GetCellValue(wbPart, cell.DataType, cell.InnerText);

            var result = new ExcelSheetValue(coords, value);
            return result;
        }
Exemple #14
0
        /// <summary>
        /// Initializes the current instance of the DataPartRelationship class.
        /// </summary>
        /// <param name="containter">The owner <see cref="OpenXmlPartContainer"/> that holds the <see cref="ReferenceRelationship"/>.</param>
        /// <param name="dataPart">The target DataPart of the reference relationship.</param>
        /// <param name="relationshipType">The relationship type of the reference relationship.</param>
        /// <param name="id">The relationship ID.</param>
        internal void Initialize(OpenXmlPartContainer containter, DataPart dataPart, string relationshipType, string id)
        {
            Debug.Assert(containter != null);
            Debug.Assert(dataPart != null);

            this.Initialize(dataPart.Uri, false, relationshipType, id);
            this.Container = containter;
            this.DataPart  = dataPart;
        }
Exemple #15
0
        public static void ApplyContent(ReportData client, OpenXmlPartContainer container, BlockItem block, TableDefinition content, Dictionary <string, string> options)
        {
            var contentblock = GetTableContentBlock(client, block);

            if (null != contentblock)
            {
                UpdateBlock(client, container, contentblock, content, options);
            }
        }
Exemple #16
0
        public ExcelSheetValue ParseCell(OpenXmlPartContainer wbPart, Cell cell)
        {
            var coords = _cellCoordinateParser.ParseCoordinates(cell.CellReference);
            var value  = _cellValueParser.GetCellValue(wbPart, cell.DataType, cell.InnerText);

            var result = new ExcelSheetValue(coords, value);

            return(result);
        }
        /// <summary>
        /// Initializes the current instance of the DataPartRelationship class.
        /// </summary>
        /// <param name="containter">The owner <see cref="OpenXmlPartContainer"/> that holds the <see cref="ReferenceRelationship"/>.</param>
        /// <param name="dataPart">The target DataPart of the reference relationship.</param>
        /// <param name="relationshipType">The relationship type of the reference relationship.</param>
        /// <param name="id">The relationship ID.</param>
        internal void Initialize(OpenXmlPartContainer containter, DataPart dataPart, string relationshipType, string id)
        {
            Debug.Assert(containter != null);
            Debug.Assert(dataPart != null);

            this.Initialize(dataPart.Uri, false, relationshipType, id);
            this.Container = containter;
            this.DataPart = dataPart;
        }
Exemple #18
0
        public static string GetNextRelationshipId(this OpenXmlPartContainer parent)
        {
            int id = parent.Parts
                     .Select(p => p.RelationshipId.StartsWith("rId") ? (int.TryParse(p.RelationshipId.Substring(3), out int number) ? number : 0) : 0)
                     .DefaultIfEmpty(0)
                     .Max() + 1;

            return($"rId{id}");
        }
Exemple #19
0
        public static void ApplyContent(ReportData client, OpenXmlPartContainer container, BlockItem block, string content)
        {
            var contentblock = GetTextContentBlock(client, block);

            if (null != contentblock)
            {
                UpdateBlock(client, container, contentblock, content);
            }
        }
 private static void addChildIdPartPairs(IList <IdPartPair> list, OpenXmlPartContainer root)
 {
     foreach (var idPartPair in root.Parts)
     {
         if (list.Where(i => i.RelationshipId == idPartPair.RelationshipId && object.ReferenceEquals(i.OpenXmlPart, idPartPair.OpenXmlPart)).Count() == 0)
         {
             list.Add(idPartPair);
             addChildIdPartPairs(list, idPartPair.OpenXmlPart);
         }
     }
 }
Exemple #21
0
 // ReSharper disable once UnusedParameter.Local
 private static void UpdatePowerPointBlock(OpenXmlPartContainer container, OpenXmlElement block, string content)
 {
     OXP.Shape shape = (OXP.Shape)block.CloneNode(true);
     OXD.Run   run   = (OXD.Run)shape.TextBody.Descendants <OXD.Run>().First().CloneNode(true);
     run.Text = new OXD.Text(content);
     OXD.Paragraph paragraph = shape.TextBody.GetFirstChild <OXD.Paragraph>();
     paragraph.RemoveAllChildren <OXD.Run>();
     OXD.EndParagraphRunProperties endP = paragraph.GetFirstChild <OXD.EndParagraphRunProperties>();
     paragraph.InsertBefore(run, endP);
     block.Parent.ReplaceChild(shape, block);
 }
Exemple #22
0
        /// <summary>
        /// Removes the custom XML parts.
        /// </summary>
        /// <param name="mainDocumentPart">The main document part.</param>
        /// <param name="customXmlParts">The custom XML parts.</param>
        public void RemoveCustomXmlParts(OpenXmlPartContainer mainDocumentPart, IList <CustomXmlPart> customXmlParts)
        {
            if (mainDocumentPart == null)
            {
                throw new ArgumentNullException("mainDocumentPart");
            }

            if (customXmlParts != null)
            {
                mainDocumentPart.DeleteParts <CustomXmlPart>(customXmlParts);
            }
        }
        /// <summary>
        /// Removes the custom XML parts.
        /// </summary>
        /// <param name="mainDocumentPart">The main document part.</param>
        /// <param name="customXmlParts">The custom XML parts.</param>
        public static void RemoveCustomXmlParts(OpenXmlPartContainer mainDocumentPart, IList<CustomXmlPart> customXmlParts)
        {
            if (mainDocumentPart == null)
            {
                throw new ArgumentNullException("mainDocumentPart");
            }

            if (customXmlParts != null)
            {
                mainDocumentPart.DeleteParts(customXmlParts);
            }
        }
        /// <summary>
        /// Creates a complete list of all parts contained in the <see cref="OpenXmlPartContainer" />.
        /// </summary>
        /// <param name="container">
        /// A <see cref="WordprocessingDocument" />, <see cref="SpreadsheetDocument" />, or
        /// <see cref="PresentationDocument" />.
        /// </param>
        /// <returns>list of <see cref="OpenXmlPart" />s contained in the <see cref="OpenXmlPartContainer" />.</returns>
        public static List <OpenXmlPart> GetAllParts(this OpenXmlPartContainer container)
        {
            // Use a HashSet so that parts are processed only once.
            var partList = new HashSet <OpenXmlPart>();

            foreach (IdPartPair p in container.Parts)
            {
                AddPart(partList, p.OpenXmlPart);
            }

            return(partList.OrderBy(p => p.ContentType).ThenBy(p => p.Uri.ToString()).ToList());
        }
 /// <summary>
 /// Returns all block contained into the container given in argument.
 /// </summary>
 /// <param name="container">Container where the block items will be found.</param>
 /// <returns>All block contained into the container given in argument.</returns>
 protected override List <BlockItem> GetBlocks(OpenXmlPartContainer container)
 {
     return(((SlidePart)container).Slide
            .Descendants <NonVisualDrawingProperties>()
            .Where(_ => !string.IsNullOrWhiteSpace(_.Description) && (_.Parent.Parent is Shape || _.Parent.Parent is GraphicFrame))
            .Select(_ => new BlockItem
     {
         OxpBlock = _.Parent.Parent,
         XBlock = XElement.Parse(_.Parent.Parent.OuterXml),
         Container = (SlidePart)container
     })
            .ToList());
 }
Exemple #26
0
        private static void UpdateBlock(ReportData client, OpenXmlPartContainer container, OpenXmlElement block, TableDefinition content, Dictionary <string, string> options)
        {
            switch (client.ReportType)
            {
            case FormatType.Word: { UpdateWordBlock(client, container, block, content, options); } break;

            case FormatType.PowerPoint: { UpdatePowerPointBlock(client, container, block, content, options); } break;

            case FormatType.Excel: { UpdateExcelBlock(client, container, block, content, options); } break;

            default: break;
            }
        }
Exemple #27
0
        private static void UpdateBlock(ReportData client, OpenXmlPartContainer container, OpenXmlElement block, string content)
        {
            switch (client.ReportType)
            {
            case FormatType.Word: { UpdateWordBlock(container, block, content); } break;

            case FormatType.PowerPoint: { UpdatePowerPointBlock(container, block, content); } break;

            case FormatType.Excel: { UpdateExcelBlock(container, block, content); } break;

            default: break;
            }
        }
 /// <summary>
 /// Returns all block contained into the container given in argument.
 /// </summary>
 /// <param name="container">Container where the block items will be found.</param>
 /// <returns>All block contained into the container given in argument.</returns>
 protected override List<BlockItem> GetBlocks(OpenXmlPartContainer container)
 {
     return ((SlidePart)container).Slide
                                  .Descendants<NonVisualDrawingProperties>()
                                  .Where(_ => !string.IsNullOrWhiteSpace(_.Description) && (_.Parent.Parent is Shape || _.Parent.Parent is GraphicFrame))
                                  .Select(_ => new BlockItem
                                               {
                                                   OxpBlock = _.Parent.Parent,
                                                   XBlock = XElement.Parse(_.Parent.Parent.OuterXml),
                                                   Container = (SlidePart)container
                                               })
                                  .ToList();
 }
        /// <summary>
        /// Get All Parts of the specified package/part in depth-first pre-order.
        /// </summary>
        /// <param name="root">package or part which can contain parts.</param>
        /// <returns>IEnumerable<OpenXmlPart> of parts in the pass-in <paramref name="root"/>.</returns>
        public static IEnumerable <OpenXmlPart> DescendantParts(this OpenXmlPartContainer root)
        {
            if (null == root)
            {
                throw new ArgumentNullException(nameof(root));
            }

            var parts   = new List <OpenXmlPart>();
            var uriList = new List <string>();

            addChildParts(parts, uriList, root);

            return(parts);
        }
Exemple #30
0
 private OpenXmlPartRootElement GetRootContainer(OpenXmlPartContainer container)
 {
     if (container is HeaderPart)
     {
         return(((HeaderPart)container).Header);
     }
     else if (container is FooterPart)
     {
         return(((FooterPart)container).Footer);
     }
     else
     {
         return(((WordprocessingDocument)container).MainDocumentPart.Document);
     }
 }
Exemple #31
0
        private static OpenXmlPartRootElement GetRootContainer(OpenXmlPartContainer container)
        {
            var _part = container as HeaderPart;

            if (_part != null)
            {
                return(_part.Header);
            }
            else if (container is FooterPart)
            {
                return(((FooterPart)container).Footer);
            }
            else
            {
                return(((WordprocessingDocument)container).MainDocumentPart.Document);
            }
        }
Exemple #32
0
        public static void BuildContent(ReportData client, OpenXmlPartContainer container, BlockItem block, string blockName, Dictionary <string, string> options)
        {
            TextBlock instance = BlockHelper.GetAssociatedBlockInstance <TextBlock>(blockName);

            if (null != instance)
            {
                LogHelper.Instance.LogDebugFormat("Start TextBlock generation : Type {0}", blockName);
                Stopwatch treatmentWatch = Stopwatch.StartNew();
                string    content        = instance.Content(client, options);
                ApplyContent(client, container, block, content);
                treatmentWatch.Stop();
                LogHelper.Instance.LogDebugFormat
                    ("End TextBlock generation ({0}) in {1} ms"
                    , blockName
                    , treatmentWatch.ElapsedMilliseconds.ToString()
                    );
            }
        }
Exemple #33
0
 public static void BuildContent(ReportData client, OpenXmlPartContainer container, BlockItem block, string blockName, Dictionary<string, string> options)
 {
     TableBlock instance = BlockHelper.GetAssociatedBlockInstance<TableBlock>(blockName);
     if (null != instance)
     {
         LogHelper.Instance.LogDebugFormat("Start TableBlock generation : Type {0}", blockName);
         Stopwatch treatmentWatch = Stopwatch.StartNew();
         TableDefinition content = instance.Content(client, options);
         if (null != content)
         {
             ApplyContent(client, container, block, content, options);
         }
         treatmentWatch.Stop();
         LogHelper.Instance.LogDebugFormat
             ("End TableBlock generation ({0}) in {1} millisecond{2}"
             , blockName
             , treatmentWatch.ElapsedMilliseconds.ToString()
             , treatmentWatch.ElapsedMilliseconds > 1 ? "s" : string.Empty
             );
     }
 }
Exemple #34
0
        private static void UpdateWordBlock(OpenXmlPartContainer container, OpenXmlElement block, string content)
        {
            OXW.Text new_text = new OXW.Text(content);
            if (!string.IsNullOrEmpty(content) && (char.IsWhiteSpace(content[0]) || char.IsWhiteSpace(content[content.Length - 1])))
            {
                new_text.Space = SpaceProcessingModeValues.Preserve;
            }
            OXW.Run           run             = new OXW.Run(new_text);
            OXW.RunProperties originalRunProp = block.Descendants <OXW.RunProperties>().FirstOrDefault();
            if (originalRunProp != null)
            {
                run.RunProperties = (OXW.RunProperties)originalRunProp.CloneNode(true);
            }
            OpenXmlElement finalBlock = run;

            if ("SdtRun" == block.Parent.GetType().Name)
            {
                // case text block in a content control
                var cbcontainer = block.Parent;
                cbcontainer?.Parent.ReplaceChild(finalBlock, cbcontainer);
            }
            else
            {
                // case text block is in a text box
                var oldTxt = block.Descendants <OXW.Run>().FirstOrDefault()?.Parent;
                oldTxt?.RemoveAllChildren();
                oldTxt?.AppendChild(finalBlock);
            }
            var docPart = container.GetPartsOfType <MainDocumentPart>().FirstOrDefault();

            if (docPart == null)
            {
                var p = container as OpenXmlPart;
                if (p != null)
                {
                    docPart = p.GetParentParts().FirstOrDefault(_ => _ is MainDocumentPart) as MainDocumentPart;
                }
            }
            docPart?.Document.Save();
        }
Exemple #35
0
        public T CopyPart <T>(T part, string id, OpenXmlPartContainer container) where T : OpenXmlPart, IFixedContentTypePart
        {
            try
            {
                T newPart = container.AddNewPart <T>(id);
                //if (newPart is OpenXmlPartContainer subContainer)
                //{
                //    foreach (var subPart in part.Parts)
                //    {
                //        CopyPart(subPart.OpenXmlPart, subPart.RelationshipId, subContainer);
                //    }
                //}
                using (var reader = part.GetStream())
                    newPart.FeedData(reader);


                // copy all external relationships
                foreach (ExternalRelationship externalRel in part.ExternalRelationships)
                {
                    newPart.AddExternalRelationship(externalRel.RelationshipType, externalRel.Uri, externalRel.Id);
                }

                // copy all hyperlink relationships
                foreach (HyperlinkRelationship hyperlinkRel in part.HyperlinkRelationships)
                {
                    newPart.AddHyperlinkRelationship(hyperlinkRel.Uri, hyperlinkRel.IsExternal, hyperlinkRel.Id);
                }

                // First, we need copy the referenced media data part.
                foreach (var dataPartReferenceRelationship in part.DataPartReferenceRelationships)
                {
                }
                return(newPart);
            }
            catch (Exception ex)
            {
                Helper.OnException(ex);
            }
            return(null);
        }
Exemple #36
0
        internal static string AddPictureToOOXMLDocument(OpenXmlPartContainer mainPart, Image image, int index, out string imageName)
        {
            //Set variables for image
            var rid = string.Format(CultureInfo.CurrentCulture, "rId{0}", index);

            imageName = string.Format(CultureInfo.CurrentCulture, "Picture {0}", index);

            //Create the imagepart as an JPEG
            while (mainPart.Parts.Any(p => p.RelationshipId == rid))
            {
                rid       = string.Format(CultureInfo.CurrentCulture, "image{0}", index++);
                imageName = string.Format(CultureInfo.CurrentCulture, "Picture {0}", index);
            }
            var imagePart = mainPart.AddNewPart <ImagePart>("image/jpeg", rid);

            //Write the image with in image part
            var bmp = new Bitmap(image);

            bmp.Save(imagePart.GetStream(), ImageFormat.Jpeg);

            return(rid);
        }
 internal static void AddStyleDefinitionPart(OpenXmlPartContainer oxpc)
 {
     new Styles().Save(oxpc.AddNewPart<StyleDefinitionsPart>());
 }
 private static DocumentSettingsPart CreateDocumentSettingsPart(OpenXmlPartContainer mainDocumentPart)
 {
     var part = mainDocumentPart.AddNewPart<DocumentSettingsPart>();
     part.Settings = new Settings();
     return part;
 }
Exemple #39
0
        private static void UpdateWordBlock(ReportData client, OpenXmlPartContainer container, OpenXmlElement block, TableDefinition content, Dictionary<string, string> options)
        {
            if (null != content && block is OXW.Table)
            {
                OXW.Table table = ((OXW.Table)block).CloneNode(true) as OXW.Table;

                OXW.TableRow headerRowTemplate = table.Descendants<OXW.TableRow>().First().CloneNode(true) as OXW.TableRow;
                OXW.TableRow contentRowTemplate = table.Descendants<OXW.TableRow>().Skip(1).First().CloneNode(true) as OXW.TableRow;

                #region Column number management
                OXW.TableGrid tablegrid = table.Descendants<OXW.TableGrid>().FirstOrDefault();
                if (null != tablegrid)
                {
                    List<OXW.GridColumn> columns = tablegrid.Descendants<OXW.GridColumn>().ToList();
                    if (null != columns && content.NbColumns != columns.Count)
                    {
                        if (content.NbColumns < columns.Count)
                        {
                            for (int i = columns.Count - 1, lim = content.NbColumns - 1; i > lim; i--)
                            {
                                tablegrid.RemoveChild<OXW.GridColumn>(columns[i]);
                            }
                        }
                        else
                        {
                            for (int i = 0, lim = content.NbColumns - columns.Count; i < lim; i++)
                            {
                                tablegrid.AppendChild<OXW.GridColumn>(new OXW.GridColumn() { Width = "1000" });
                            }
                        }
                    }
                }
                #endregion Column number management

                ModifyWordRowTextContent(headerRowTemplate, string.Empty);
                ModifyWordRowTextContent(contentRowTemplate, string.Empty);

                int idx = 0;
                int nbrow = 0;
                List<OXW.TableCell> headerCells = headerRowTemplate.Descendants<OXW.TableCell>().Select(_ => _.CloneNode(true) as OXW.TableCell).ToList();
                List<OXW.TableCell> contentCells = contentRowTemplate.Descendants<OXW.TableCell>().Select(_ => _.CloneNode(true) as OXW.TableCell).ToList();
                headerRowTemplate.RemoveAllChildren<OXW.TableCell>();
                OXW.TableRow row = headerRowTemplate;
                int headerCellsCount = headerCells.Count;
                int contentCellsCount = headerCells.Count;

                table.RemoveAllChildren<OXW.TableRow>();
                foreach (var item in content.Data)
                {
                    if (null != item)
                    {
                        OXW.TableCell cell = null;
                        if (content.HasColumnHeaders && 0 == nbrow)
                        {
                            cell = headerCells[idx % headerCellsCount].CloneNode(true) as OXW.TableCell;
                        }
                        else
                        {
                            cell = contentCells[idx % contentCellsCount].CloneNode(true) as OXW.TableCell;
                        }
                        ModifyWordCellTextContent(cell, item);
                        row.Append(cell);
                    }

                    idx = ++idx % content.NbColumns;
                    if (0 == idx)
                    {
                        if (null != row)
                        {
                            table.Append(row);
                            nbrow++;
                        }
                        row = contentRowTemplate.CloneNode(true) as OXW.TableRow;
                        row.RemoveAllChildren<OXW.TableCell>();
                    }
                }
                var blockSdt = block.Ancestors<OXW.SdtBlock>().First();
                blockSdt.Parent.ReplaceChild(table, blockSdt);
            }
            else
            {
                LogHelper.Instance.LogErrorFormat("Impossible to load data in Table block with a block source of type \"{0}\"", null != block ? block.GetType().ToString() : "null");
            }
        }
Exemple #40
0
        private static void UpdatePowerPointBlock(ReportData client, OpenXmlPartContainer container, OpenXmlElement block, TableDefinition content, Dictionary<string, string> options)
        {
            if (null != content && block is OXP.GraphicFrame)
            {
                OXD.Table initTable = (OXD.Table)block.Descendants<OXD.Table>().FirstOrDefault();
                if (null != initTable)
                {
                    try
                    {
                        OXD.Table table = initTable.CloneNode(true) as OXD.Table;
                        OXD.TableRow headerRowTemplate = table.Descendants<OXD.TableRow>().First().CloneNode(true) as OXD.TableRow;
                        OXD.TableRow contentRowTemplate = table.Descendants<OXD.TableRow>().Skip(1).First().CloneNode(true) as OXD.TableRow;

                        ModifyPowerPointRowTextContent(headerRowTemplate, string.Empty);
                        ModifyPowerPointRowTextContent(contentRowTemplate, string.Empty);

                        #region Column Number Management
                        List<OXD.GridColumn> columns = table.TableGrid.Descendants<OXD.GridColumn>().ToList();
                        if (columns.Count < content.NbColumns)
                        {
                            int nbNewColumn = content.NbColumns - columns.Count;
                            for (int i = 0, lim = nbNewColumn; i < lim; i++)
                            {
                                AddNewGridColumn(table.TableGrid, headerRowTemplate, contentRowTemplate);
                            }
                        } else if (columns.Count > content.NbColumns) {
                            for (int i = content.NbColumns, lim = columns.Count; i < lim; i++) {
                                RemoveLastGridColumn(table.TableGrid);
                            }
                        }
                        #endregion Column Number Management

                        int idx = 0;
                        int nbrow = 0;
                        List<OXD.TableCell> headerCells = headerRowTemplate.Descendants<OXD.TableCell>().Select(_ => _.CloneNode(true) as OXD.TableCell).ToList();
                        List<OXD.TableCell> contentCells = contentRowTemplate.Descendants<OXD.TableCell>().Select(_ => _.CloneNode(true) as OXD.TableCell).ToList();
                        headerRowTemplate.RemoveAllChildren<OXD.TableCell>();
                        OXD.TableRow row = headerRowTemplate;

                        table.RemoveAllChildren<OXD.TableRow>();
                        foreach (var item in content.Data)
                        {
                            OXD.TableCell cell = null;
                            if (content.HasColumnHeaders && 0 == nbrow)
                            {
                                cell = headerCells[idx].CloneNode(true) as OXD.TableCell;
                            }
                            else
                            {
                                cell = contentCells[idx].CloneNode(true) as OXD.TableCell;
                            }
                            ModifyPowerPointCellTextContent(cell, item);

                            //row.Append(cell); => in office 2016, element <extLst> should absolutely be in the latest position in a row
                            row.InsertBefore<OXD.TableCell>(cell, row.Descendants<OXD.ExtensionList>().FirstOrDefault());

                            idx = ++idx % content.NbColumns;
                            if (0 == idx)
                            {
                                if (null != row)
                                {
                                    table.Append(row);
                                    nbrow++;
                                }
                                row = contentRowTemplate.CloneNode(true) as OXD.TableRow;
                                row.RemoveAllChildren<OXD.TableCell>();
                            }
                        }
                        initTable.Parent.ReplaceChild(table, initTable);
                    }
                    catch (Exception exception)
                    {
                        LogHelper.Instance.LogErrorFormat("An unhandled exception was thrown during table block content generation : '{0}'", exception.ToString());
                        if (null != initTable)
                        {
                            if (null != initTable.Descendants<OXD.TableRow>() && 1 > initTable.Descendants<OXD.TableRow>().Count())
                            {
                                foreach (var row in initTable.Descendants<OXD.TableRow>().Skip(1))
                                {
                                    ModifyPowerPointRowTextContent(row, string.Empty);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                LogHelper.Instance.LogErrorFormat("Impossible to load data in table block with a block source of type \"{0}\"", null != block ? block.GetType().ToString() : "null");
            }
        }
Exemple #41
0
 private static void UpdateExcelBlock(ReportData client, OpenXmlPartContainer container, OpenXmlElement block, TableDefinition content, Dictionary<string, string> options)
 {
     // TODO : Finalize Excel alimentation
     throw new NotImplementedException();
 }
Exemple #42
0
 private static void UpdateBlock(ReportData client, OpenXmlPartContainer container, OpenXmlElement block, TableDefinition content, Dictionary<string, string> options)
 {
     switch (client.ReportType)
     {
         case FormatType.Word: { UpdateWordBlock(client, container, block, content, options); } break;
         case FormatType.PowerPoint: { UpdatePowerPointBlock(client, container, block, content, options); } break;
         case FormatType.Excel: { UpdateExcelBlock(client, container, block, content, options); } break;
         default: break;
     }
 }
        /// <summary>
        /// Creates a new instance of the DataPartRelationship class based on the relationship type.
        /// </summary>
        /// <param name="containter">The owner <see cref="OpenXmlPartContainer"/> that holds the <see cref="ReferenceRelationship"/>.</param>
        /// <param name="dataPart">The target DataPart of the reference relationship.</param>
        /// <param name="relationshipType">The relationship type of the reference relationship.</param>
        /// <param name="id">The relationship ID.</param>
        internal static DataPartReferenceRelationship CreateDataPartReferenceRelationship(OpenXmlPartContainer containter, DataPart dataPart, string relationshipType, string id)
        {
            Debug.Assert(containter != null);
            Debug.Assert(dataPart != null);

            DataPartReferenceRelationship dataPartReferenceRelationship;

            switch (relationshipType)
            {
                case MediaReferenceRelationship.RelationshipTypeConst:
                    dataPartReferenceRelationship = new MediaReferenceRelationship((MediaDataPart)dataPart, id);
                    break;

                case AudioReferenceRelationship.RelationshipTypeConst:
                    dataPartReferenceRelationship = new AudioReferenceRelationship((MediaDataPart)dataPart, id);
                    break;

                case VideoReferenceRelationship.RelationshipTypeConst:
                    dataPartReferenceRelationship = new VideoReferenceRelationship((MediaDataPart)dataPart, id);
                    break;

                default:
                    throw new ArgumentOutOfRangeException("relationshipType");
            }
            dataPartReferenceRelationship.Container = containter;
            return dataPartReferenceRelationship;
        }
 private OpenXmlPartRootElement GetRootContainer(OpenXmlPartContainer container)
 {
     if (container is HeaderPart)
     {
         return ((HeaderPart)container).Header;
     }
     else if (container is FooterPart)
     {
         return ((FooterPart)container).Footer;
     }
     else
     {
         return ((WordprocessingDocument)container).MainDocumentPart.Document;
     }
 }
        /// <summary>
        /// Returns all block contained into the container given in argument.
        /// </summary>
        /// <param name="container">Container where the block items will be found.</param>
        /// <returns>All block contained into the container given in argument.</returns>
        protected override List<BlockItem> GetBlocks(OpenXmlPartContainer container)
        {
            // TODO : Finalize Excel alimentation

            throw new NotImplementedException();
        }
Exemple #46
0
 public StylesPart(OpenXmlPartContainer parent)
     : base(parent, 0)
 {
 }
 /// <summary>
 /// Returns all block contained into the container given in argument.
 /// </summary>
 /// <param name="container">Container where the block items will be found.</param>
 /// <returns>All block contained into the container given in argument.</returns>
 protected override List<BlockItem> GetBlocks(OpenXmlPartContainer container)
 {
     OpenXmlPartRootElement rootContainer = GetRootContainer(container);
     var blocks = rootContainer.Descendants<SdtElement>()
                               .Select(_ => new BlockItem
                                            {
                                                OxpBlock = _,
                                                XBlock = XElement.Parse(_.OuterXml),
                                                Container = container
                                            })
                               .ToList();
     var addblocks = rootContainer.Descendants<DocProperties>()
                                  .Where(_ => null != _.Description
                                              && _.Description.HasValue
                                              && !string.IsNullOrWhiteSpace(_.Description.Value)
                                              && (_.Parent.Parent is Drawing || _.Parent.Parent is Table))
                                  .Select(_ => new BlockItem
                                  {
                                      OxpBlock = _.Parent.Parent,
                                      XBlock = XElement.Parse(_.Parent.Parent.OuterXml),
                                      Container = container
                                  })
                                  .ToList(); ;
     blocks.AddRange(addblocks);
     return blocks;
 }