Search code examples
c#openxmlopenxml-sdkpresentationml

Presentation created in C# with the Open XML SDK is corrupted and blank when opened


Problem

I am trying to create a PowerPoint presentation in C# with Visual Studio using the Open XML SDK.

The presentation I create contains one slide with one table with 3 rows and 2 columns.

When I try to open the PowerPoint presentation created by the program, I am presented with the following error message:

PowerPoint found a problem with content in test3.pptx.
PowerPoint can attempt to repair the presentation.

If you trust the source of this presentation, click Repair.

When I click Repair, I am presented with another error message:

PowerPoint couldn't read some content in test3.pptx - Repaired and removed it.

Please check your presentation to see if the rest looks ok.

When I click Ok and check the contents of the presentation, it is empty.

QUESTION

How should I modify the program, so users can open the presentations without problems?

  • Am I using the wrong version of the Open XML SDK?
  • Is there something wrong with the code I've written?
  • Are there tools I can use to assist me in tracking down the error?
  • Other?

The version of PowerPoint I use to open the .pptx file

Microsoft® PowerPoint® for Microsoft 365 MSO (Version 2310 Build 16.0.16924.20054) 64-bit

My console project looks like this

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
  </ItemGroup>
</Project>

My main program looks like this

var builder = new OpenXMLBuilder.Test3();
builder.Doit(args);

My source code looks like this

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using D = DocumentFormat.OpenXml.Drawing;

#region disable_warnings
// Remove unnecessary suppression
#pragma warning disable IDE0079
// Member 'x' does not access instance data and can be marked as static
#pragma warning disable CA1822
// Remove unused parameter 'x'
#pragma warning disable IDE0060
// 'using' statement can be simplified
#pragma warning disable IDE0063
// 'new' expression can be simplified
#pragma warning disable IDE0090
// Object initialization can be simplified
#pragma warning disable IDE0017
#endregion

namespace OpenXMLBuilder
{
    class Test3
    {
        public void Doit(string[] args)
        {
            string filepath = "test3.pptx";
            CreatePresentation(filepath);
        }

        public static void CreatePresentation(string filepath)
        {
            // Create a presentation at a specified file path.
            using (PresentationDocument presentationDocument = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation))
            {
                PresentationPart presentationPart = presentationDocument.AddPresentationPart();
                presentationPart.Presentation = new Presentation();
                CreateSlide(presentationPart);
            }
        }

        private static void CreateSlide(PresentationPart presentationPart)
        {
            // Create the SlidePart.
            SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
            slidePart.Slide = new Slide(new CommonSlideData(new ShapeTree()));

            // Declare and instantiate the table
            D.Table table = new D.Table();

            // Define the columns
            D.TableGrid tableGrid = new D.TableGrid();
            tableGrid.Append(new D.GridColumn() { Width = 3124200 });
            tableGrid.Append(new D.GridColumn() { Width = 3124200 });

            // Append the TableGrid to the table
            table.Append(tableGrid);

            // Create the rows and cells
            for (int i = 0; i < 3; i++) // 3 rows
            {
                D.TableRow row = new D.TableRow() { Height = 370840 };
                for (int j = 0; j < 2; j++) // 2 columns
                {
                    D.TableCell cell = new D.TableCell();
                    D.TextBody body = new D.TextBody(new D.BodyProperties(),
                                                         new D.ListStyle(),
                                                         new D.Paragraph(new D.Run(new D.Text($"Cell {i + 1},{j + 1}"))));
                    cell.Append(body);
                    cell.Append(new D.TableCellProperties());
                    row.Append(cell);
                }
                table.Append(row);
            }

            // Create a GraphicFrame to hold the table
            GraphicFrame graphicFrame = new GraphicFrame();
            graphicFrame.NonVisualGraphicFrameProperties = new NonVisualGraphicFrameProperties(
                new NonVisualDrawingProperties() { Id = 1026, Name = "Table" },
                new NonVisualGraphicFrameDrawingProperties(),
                new ApplicationNonVisualDrawingProperties());
            graphicFrame.Transform = new Transform(new D.Offset() { X = 0L, Y = 0L }, new D.Extents() { Cx = 0L, Cy = 0L });
            graphicFrame.Graphic = new D.Graphic(new D.GraphicData(table)
            {
                Uri = "http://schemas.openxmlformats.org/drawingml/2006/table"
            });
            // Sanity check
            if (slidePart.Slide.CommonSlideData == null)
                throw new InvalidOperationException("CreateSlide: CommonSlideData is null");
            if (slidePart.Slide.CommonSlideData.ShapeTree == null)
                throw new InvalidOperationException("CreateSlide: ShapeTree is null");
            // Append the GraphicFrame to the SlidePart
            slidePart.Slide.CommonSlideData.ShapeTree.AppendChild(graphicFrame);
            // Save the slide part
            slidePart.Slide.Save();

            // Create slide master
            SlideMasterPart slideMasterPart = presentationPart.AddNewPart<SlideMasterPart>();
            slideMasterPart.SlideMaster = new SlideMaster(new CommonSlideData(new ShapeTree()));
            slideMasterPart.SlideMaster.Save();

            // Create slide layout
            SlideLayoutPart slideLayoutPart = slideMasterPart.AddNewPart<SlideLayoutPart>();
            slideLayoutPart.SlideLayout = new SlideLayout(new CommonSlideData(new ShapeTree()));
            slideLayoutPart.SlideLayout.Save();
            // Create unique id for the slide
            presentationPart.Presentation.SlideIdList = new SlideIdList(new SlideId()
            {
                Id = 256U,
                RelationshipId = presentationPart.GetIdOfPart(slidePart)
            });
            // Set the size
            presentationPart.Presentation.SlideSize = new SlideSize() { Cx = 9144000, Cy = 6858000 };

            // Save the presentation
            presentationPart.Presentation.Save();
        }
    } // class
} // namespace

Solution

  • I was able to create a starting point similar to your (create a presentation and add a table to it). The code is not super easy nor short, but I wasn't able to reduce it. Still, it produces a new powerpoint with a table in the first page!

    Code took by Microsoft DOC and Microsoft sample

    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Presentation;
    using A = DocumentFormat.OpenXml.Drawing;
    using D = DocumentFormat.OpenXml.Drawing;
    using P = DocumentFormat.OpenXml.Presentation;
    using P14 = DocumentFormat.OpenXml.Office2010.PowerPoint;
    
    #region disable_warnings
    // Remove unnecessary suppression
    #pragma warning disable IDE0079
    // Member 'x' does not access instance data and can be marked as static
    #pragma warning disable CA1822
    // Remove unused parameter 'x'
    #pragma warning disable IDE0060
    // 'using' statement can be simplified
    #pragma warning disable IDE0063
    // 'new' expression can be simplified
    #pragma warning disable IDE0090
    // Object initialization can be simplified
    #pragma warning disable IDE0017
    #endregion
    
    namespace OpenXMLBuilder
    {
        class Test2
        {
            public void Doit(string[] args)
            {
                string filepath = "test3.pptx";
                CreatePresentation(filepath);
            }
    
            public static void CreatePresentation(string filepath)
            {
                // Create a presentation at a specified file path. The presentation document type is pptx, by default.
                PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation);
                PresentationPart presentationPart = presentationDoc.AddPresentationPart();
                presentationPart.Presentation = new Presentation();
    
                CreatePresentationParts(presentationPart);
    
                CreateTableInLastSlide(presentationDoc);
                //Close the presentation handle
                presentationPart.Presentation.Save();
                presentationDoc.Close();
            }
    
            private static void CreatePresentationParts(PresentationPart presentationPart)
            {
                SlideMasterIdList slideMasterIdList1 = new SlideMasterIdList(new SlideMasterId() { Id = (UInt32Value)2147483648U, RelationshipId = "rId1" });
                SlideIdList slideIdList1 = new SlideIdList(new SlideId() { Id = (UInt32Value)256U, RelationshipId = "rId2" });
                SlideSize slideSize1 = new SlideSize() { Cx = 9144000, Cy = 6858000, Type = SlideSizeValues.Screen4x3 };
                NotesSize notesSize1 = new NotesSize() { Cx = 6858000, Cy = 9144000 };
                DefaultTextStyle defaultTextStyle1 = new DefaultTextStyle();
    
                presentationPart.Presentation.Append(slideMasterIdList1, slideIdList1, slideSize1, notesSize1, defaultTextStyle1);
    
                SlidePart slidePart1;
                SlideLayoutPart slideLayoutPart1;
                SlideMasterPart slideMasterPart1;
                ThemePart themePart1;
    
    
                slidePart1 = CreateSlidePart(presentationPart);
                slideLayoutPart1 = CreateSlideLayoutPart(slidePart1);
                slideMasterPart1 = CreateSlideMasterPart(slideLayoutPart1);
                themePart1 = CreateTheme(slideMasterPart1);
    
                slideMasterPart1.AddPart(slideLayoutPart1, "rId1");
                presentationPart.AddPart(slideMasterPart1, "rId1");
                presentationPart.AddPart(themePart1, "rId5");
            }
    
            private static SlidePart CreateSlidePart(PresentationPart presentationPart)
            {
                // Create a GraphicFrame to hold the table
                SlidePart slidePart1 = presentationPart.AddNewPart<SlidePart>("rId2");
    
                slidePart1.Slide = new Slide(
                        new CommonSlideData(
                            new ShapeTree(
                                new P.NonVisualGroupShapeProperties(
                                    new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
                                    new P.NonVisualGroupShapeDrawingProperties(),
                                    new ApplicationNonVisualDrawingProperties()),
                                new GroupShapeProperties(new D.TransformGroup()),
                                new P.Shape(
                                    new P.NonVisualShapeProperties(
                                        new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title 1" },
                                        new P.NonVisualShapeDrawingProperties(new D.ShapeLocks() { NoGrouping = true }),
                                        new ApplicationNonVisualDrawingProperties(new PlaceholderShape())),
                                    new P.ShapeProperties(),
                                    new P.TextBody(
                                        new D.BodyProperties(),
                                        new D.ListStyle(),
                                        new D.Paragraph(new D.EndParagraphRunProperties() { Language = "en-US" }))))),
                        new ColorMapOverride(new D.MasterColorMapping()));
    
                return slidePart1;
            }
    
            private static SlideLayoutPart CreateSlideLayoutPart(SlidePart slidePart1)
            {
                SlideLayoutPart slideLayoutPart1 = slidePart1.AddNewPart<SlideLayoutPart>("rId1");
                SlideLayout slideLayout = new SlideLayout(
                new CommonSlideData(new ShapeTree(
                  new P.NonVisualGroupShapeProperties(
                  new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
                  new P.NonVisualGroupShapeDrawingProperties(),
                  new ApplicationNonVisualDrawingProperties()),
                  new GroupShapeProperties(new D.TransformGroup()),
                  new P.Shape(
                  new P.NonVisualShapeProperties(
                    new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "" },
                    new P.NonVisualShapeDrawingProperties(new D.ShapeLocks() { NoGrouping = true }),
                    new ApplicationNonVisualDrawingProperties(new PlaceholderShape())),
                  new P.ShapeProperties(),
                  new P.TextBody(
                    new D.BodyProperties(),
                    new D.ListStyle(),
                    new D.Paragraph(new D.EndParagraphRunProperties()))))),
                new ColorMapOverride(new D.MasterColorMapping()));
                slideLayoutPart1.SlideLayout = slideLayout;
                return slideLayoutPart1;
            }
    
            private static SlideMasterPart CreateSlideMasterPart(SlideLayoutPart slideLayoutPart1)
            {
                SlideMasterPart slideMasterPart1 = slideLayoutPart1.AddNewPart<SlideMasterPart>("rId1");
                SlideMaster slideMaster = new SlideMaster(
                new CommonSlideData(new ShapeTree(
                  new P.NonVisualGroupShapeProperties(
                  new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" },
                  new P.NonVisualGroupShapeDrawingProperties(),
                  new ApplicationNonVisualDrawingProperties()),
                  new GroupShapeProperties(new D.TransformGroup()),
                  new P.Shape(
                  new P.NonVisualShapeProperties(
                    new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title Placeholder 1" },
                    new P.NonVisualShapeDrawingProperties(new D.ShapeLocks() { NoGrouping = true }),
                    new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title })),
                  new P.ShapeProperties(),
                  new P.TextBody(
                    new D.BodyProperties(),
                    new D.ListStyle(),
                    new D.Paragraph())))),
                new P.ColorMap() { Background1 = D.ColorSchemeIndexValues.Light1, Text1 = D.ColorSchemeIndexValues.Dark1, Background2 = D.ColorSchemeIndexValues.Light2, Text2 = D.ColorSchemeIndexValues.Dark2, Accent1 = D.ColorSchemeIndexValues.Accent1, Accent2 = D.ColorSchemeIndexValues.Accent2, Accent3 = D.ColorSchemeIndexValues.Accent3, Accent4 = D.ColorSchemeIndexValues.Accent4, Accent5 = D.ColorSchemeIndexValues.Accent5, Accent6 = D.ColorSchemeIndexValues.Accent6, Hyperlink = D.ColorSchemeIndexValues.Hyperlink, FollowedHyperlink = D.ColorSchemeIndexValues.FollowedHyperlink },
                new SlideLayoutIdList(new SlideLayoutId() { Id = (UInt32Value)2147483649U, RelationshipId = "rId1" }),
                new TextStyles(new TitleStyle(), new BodyStyle(), new OtherStyle()));
                slideMasterPart1.SlideMaster = slideMaster;
    
                return slideMasterPart1;
            }
    
            private static ThemePart CreateTheme(SlideMasterPart slideMasterPart1)
            {
                ThemePart themePart1 = slideMasterPart1.AddNewPart<ThemePart>("rId5");
                D.Theme theme1 = new D.Theme() { Name = "Office Theme" };
    
                D.ThemeElements themeElements1 = new D.ThemeElements(
                new D.ColorScheme(
                  new D.Dark1Color(new D.SystemColor() { Val = D.SystemColorValues.WindowText, LastColor = "000000" }),
                  new D.Light1Color(new D.SystemColor() { Val = D.SystemColorValues.Window, LastColor = "FFFFFF" }),
                  new D.Dark2Color(new D.RgbColorModelHex() { Val = "1F497D" }),
                  new D.Light2Color(new D.RgbColorModelHex() { Val = "EEECE1" }),
                  new D.Accent1Color(new D.RgbColorModelHex() { Val = "4F81BD" }),
                  new D.Accent2Color(new D.RgbColorModelHex() { Val = "C0504D" }),
                  new D.Accent3Color(new D.RgbColorModelHex() { Val = "9BBB59" }),
                  new D.Accent4Color(new D.RgbColorModelHex() { Val = "8064A2" }),
                  new D.Accent5Color(new D.RgbColorModelHex() { Val = "4BACC6" }),
                  new D.Accent6Color(new D.RgbColorModelHex() { Val = "F79646" }),
                  new D.Hyperlink(new D.RgbColorModelHex() { Val = "0000FF" }),
                  new D.FollowedHyperlinkColor(new D.RgbColorModelHex() { Val = "800080" }))
                { Name = "Office" },
                  new D.FontScheme(
                  new D.MajorFont(
                  new D.LatinFont() { Typeface = "Calibri" },
                  new D.EastAsianFont() { Typeface = "" },
                  new D.ComplexScriptFont() { Typeface = "" }),
                  new D.MinorFont(
                  new D.LatinFont() { Typeface = "Calibri" },
                  new D.EastAsianFont() { Typeface = "" },
                  new D.ComplexScriptFont() { Typeface = "" }))
                  { Name = "Office" },
                  new D.FormatScheme(
                  new D.FillStyleList(
                  new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }),
                  new D.GradientFill(
                    new D.GradientStopList(
                    new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 50000 },
                      new D.SaturationModulation() { Val = 300000 })
                    { Val = D.SchemeColorValues.PhColor })
                    { Position = 0 },
                    new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 37000 },
                     new D.SaturationModulation() { Val = 300000 })
                    { Val = D.SchemeColorValues.PhColor })
                    { Position = 35000 },
                    new D.GradientStop(new D.SchemeColor(new D.Tint() { Val = 15000 },
                     new D.SaturationModulation() { Val = 350000 })
                    { Val = D.SchemeColorValues.PhColor })
                    { Position = 100000 }
                    ),
                    new D.LinearGradientFill() { Angle = 16200000, Scaled = true }),
                  new D.NoFill(),
                  new D.PatternFill(),
                  new D.GroupFill()),
                  new D.LineStyleList(
                  new D.Outline(
                    new D.SolidFill(
                    new D.SchemeColor(
                      new D.Shade() { Val = 95000 },
                      new D.SaturationModulation() { Val = 105000 })
                    { Val = D.SchemeColorValues.PhColor }),
                    new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
                  {
                      Width = 9525,
                      CapType = D.LineCapValues.Flat,
                      CompoundLineType = D.CompoundLineValues.Single,
                      Alignment = D.PenAlignmentValues.Center
                  },
                  new D.Outline(
                    new D.SolidFill(
                    new D.SchemeColor(
                      new D.Shade() { Val = 95000 },
                      new D.SaturationModulation() { Val = 105000 })
                    { Val = D.SchemeColorValues.PhColor }),
                    new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
                  {
                      Width = 9525,
                      CapType = D.LineCapValues.Flat,
                      CompoundLineType = D.CompoundLineValues.Single,
                      Alignment = D.PenAlignmentValues.Center
                  },
                  new D.Outline(
                    new D.SolidFill(
                    new D.SchemeColor(
                      new D.Shade() { Val = 95000 },
                      new D.SaturationModulation() { Val = 105000 })
                    { Val = D.SchemeColorValues.PhColor }),
                    new D.PresetDash() { Val = D.PresetLineDashValues.Solid })
                  {
                      Width = 9525,
                      CapType = D.LineCapValues.Flat,
                      CompoundLineType = D.CompoundLineValues.Single,
                      Alignment = D.PenAlignmentValues.Center
                  }),
                  new D.EffectStyleList(
                  new D.EffectStyle(
                    new D.EffectList(
                    new D.OuterShadow(
                      new D.RgbColorModelHex(
                      new D.Alpha() { Val = 38000 })
                      { Val = "000000" })
                    { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })),
                  new D.EffectStyle(
                    new D.EffectList(
                    new D.OuterShadow(
                      new D.RgbColorModelHex(
                      new D.Alpha() { Val = 38000 })
                      { Val = "000000" })
                    { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false })),
                  new D.EffectStyle(
                    new D.EffectList(
                    new D.OuterShadow(
                      new D.RgbColorModelHex(
                      new D.Alpha() { Val = 38000 })
                      { Val = "000000" })
                    { BlurRadius = 40000L, Distance = 20000L, Direction = 5400000, RotateWithShape = false }))),
                  new D.BackgroundFillStyleList(
                  new D.SolidFill(new D.SchemeColor() { Val = D.SchemeColorValues.PhColor }),
                  new D.GradientFill(
                    new D.GradientStopList(
                    new D.GradientStop(
                      new D.SchemeColor(new D.Tint() { Val = 50000 },
                        new D.SaturationModulation() { Val = 300000 })
                      { Val = D.SchemeColorValues.PhColor })
                    { Position = 0 },
                    new D.GradientStop(
                      new D.SchemeColor(new D.Tint() { Val = 50000 },
                        new D.SaturationModulation() { Val = 300000 })
                      { Val = D.SchemeColorValues.PhColor })
                    { Position = 0 },
                    new D.GradientStop(
                      new D.SchemeColor(new D.Tint() { Val = 50000 },
                        new D.SaturationModulation() { Val = 300000 })
                      { Val = D.SchemeColorValues.PhColor })
                    { Position = 0 }),
                    new D.LinearGradientFill() { Angle = 16200000, Scaled = true }),
                  new D.GradientFill(
                    new D.GradientStopList(
                    new D.GradientStop(
                      new D.SchemeColor(new D.Tint() { Val = 50000 },
                        new D.SaturationModulation() { Val = 300000 })
                      { Val = D.SchemeColorValues.PhColor })
                    { Position = 0 },
                    new D.GradientStop(
                      new D.SchemeColor(new D.Tint() { Val = 50000 },
                        new D.SaturationModulation() { Val = 300000 })
                      { Val = D.SchemeColorValues.PhColor })
                    { Position = 0 }),
                    new D.LinearGradientFill() { Angle = 16200000, Scaled = true })))
                  { Name = "Office" });
    
                theme1.Append(themeElements1);
                theme1.Append(new D.ObjectDefaults());
                theme1.Append(new D.ExtraColorSchemeList());
    
                themePart1.Theme = theme1;
                return themePart1;
    
            }
    
            public static void CreateTableInLastSlide(PresentationDocument presentationDocument)
            {
                // Get the presentation Part of the presentation document
                PresentationPart presentationPart = presentationDocument.PresentationPart;
    
                // Get the Slide Id collection of the presentation document
                var slideIdList = presentationPart.Presentation.SlideIdList;
    
                if (slideIdList == null)
                {
                    throw new NullReferenceException("The number of slide is empty, please select a ppt with a slide at least again");
                }
    
                // Get all Slide Part of the presentation document
                var list = slideIdList.ChildElements
                            .Cast<SlideId>()
                            .Select(x => presentationPart.GetPartById(x.RelationshipId))
                            .Cast<SlidePart>();
    
                // Get the last Slide Part of the presentation document
                var tableSlidePart = (SlidePart)list.Last();
    
                // Declare and instantiate the graphic Frame of the new slide
                GraphicFrame graphicFrame = tableSlidePart.Slide.CommonSlideData.ShapeTree.AppendChild(new GraphicFrame());
    
                // Specify the required Frame properties of the graphicFrame
                ApplicationNonVisualDrawingPropertiesExtension applicationNonVisualDrawingPropertiesExtension = new ApplicationNonVisualDrawingPropertiesExtension() { Uri = "{D42A27DB-BD31-4B8C-83A1-F6EECF244321}" };
                P14.ModificationId modificationId1 = new P14.ModificationId() { Val = 3229994563U };
                modificationId1.AddNamespaceDeclaration("p14", "http://schemas.microsoft.com/office/powerpoint/2010/main");
                applicationNonVisualDrawingPropertiesExtension.Append(modificationId1);
                graphicFrame.NonVisualGraphicFrameProperties = new NonVisualGraphicFrameProperties
                (new NonVisualDrawingProperties() { Id = 5, Name = "table 1" },
                new NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoGrouping = true }),
                new ApplicationNonVisualDrawingProperties(new ApplicationNonVisualDrawingPropertiesExtensionList(applicationNonVisualDrawingPropertiesExtension)));
    
                graphicFrame.Transform = new Transform(new A.Offset() { X = 1650609L, Y = 4343400L }, new A.Extents() { Cx = 6096000L, Cy = 741680L });
    
                // Specify the Griaphic of the graphic Frame
                graphicFrame.Graphic = new A.Graphic(new A.GraphicData(GenerateTable()) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/table" });
                presentationPart.Presentation.Save();
            }
    
            /// <summary>
            /// Generate Table as below order:
            /// a:tbl(Table) ->a:tr(TableRow)->a:tc(TableCell)
            /// We can return TableCell object with CreateTextCell method
            /// and Append the TableCell object to TableRow 
            /// </summary>
            /// <returns>Table Object</returns>
            private static A.Table GenerateTable()
            {
                string[,] tableSources = new string[,] { { "name", "age" }, { "Tom", "25" } };
    
                // Declare and instantiate table 
                A.Table table = new A.Table();
    
                // Specify the required table properties for the table
                A.TableProperties tableProperties = new A.TableProperties() { FirstRow = true, BandRow = true };
                A.TableStyleId tableStyleId = new A.TableStyleId();
                tableStyleId.Text = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}";
    
                tableProperties.Append(tableStyleId);
    
                // Declare and instantiate tablegrid and colums
                A.TableGrid tableGrid1 = new A.TableGrid();
                A.GridColumn gridColumn1 = new A.GridColumn() { Width = 3048000L };
                A.GridColumn gridColumn2 = new A.GridColumn() { Width = 3048000L };
    
                tableGrid1.Append(gridColumn1);
                tableGrid1.Append(gridColumn2);
                table.Append(tableProperties);
                table.Append(tableGrid1);
                for (int row = 0; row < tableSources.GetLength(0); row++)
                {
                    // Instantiate the table row
                    A.TableRow tableRow = new A.TableRow() { Height = 370840L };
                    for (int column = 0; column < tableSources.GetLength(1); column++)
                    {
                        tableRow.Append(CreateTextCell(tableSources.GetValue(row, column).ToString()));
                    }
    
                    table.Append(tableRow);
                }
    
                return table;
            }
    
            /// <summary>
            /// Create table cell with the below order:
            /// a:tc(TableCell)->a:txbody(TextBody)->a:p(Paragraph)->a:r(Run)->a:t(Text)
            /// </summary>
            /// <param name="text">Inserted Text in Cell</param>
            /// <returns>Return TableCell object</returns>
            private static A.TableCell CreateTextCell(string text)
            {
                if (string.IsNullOrEmpty(text))
                {
                    text = string.Empty;
                }
    
                // Declare and instantiate the table cell 
                // Create table cell with the below order:
                // a:tc(TableCell)->a:txbody(TextBody)->a:p(Paragraph)->a:r(Run)->a:t(Text)
                A.TableCell tableCell = new A.TableCell();
    
                //  Declare and instantiate the text body
                A.TextBody textBody = new A.TextBody();
                A.BodyProperties bodyProperties = new A.BodyProperties();
                A.ListStyle listStyle = new A.ListStyle();
    
                A.Paragraph paragraph = new A.Paragraph();
                A.Run run = new A.Run();
                A.RunProperties runProperties = new A.RunProperties() { Language = "en-US", Dirty = false, SmartTagClean = false };
                A.Text text2 = new A.Text();
                text2.Text = text;
                run.Append(runProperties);
                run.Append(text2);
                A.EndParagraphRunProperties endParagraphRunProperties = new A.EndParagraphRunProperties() { Language = "en-US", Dirty = false };
    
                paragraph.Append(run);
                paragraph.Append(endParagraphRunProperties);
                textBody.Append(bodyProperties);
                textBody.Append(listStyle);
                textBody.Append(paragraph);
    
                A.TableCellProperties tableCellProperties = new A.TableCellProperties();
                tableCell.Append(textBody);
                tableCell.Append(tableCellProperties);
    
                return tableCell;
            }
        }
    }