使用 Open XML SDK 在 C# 中创建的演示文稿在打开时已损坏且为空

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

提问人:GoWiser 提问时间:11/10/2023 最后编辑:GoWiser 更新时间:11/16/2023 访问量:98

问:

问题

我正在尝试使用 Visual Studio 创建一个 PowerPoint 演示文稿。C#Open XML SDK

我创建的演示文稿包含一张幻灯片和一个表格,表格有 3 行和 2 列。

当我尝试打开由该程序创建的 PowerPoint 演示文稿时,出现以下错误消息:

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.

当我单击“修复”时,我看到另一条错误消息:

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

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

当我单击“确定”并检查演示文稿的内容时,它是空的。

问题

我应该如何修改程序,以便用户可以毫无问题地打开演示文稿?

  • 我是否使用了错误版本的 ?Open XML SDK
  • 我写的代码有问题吗?
  • 我可以使用哪些工具来帮助我跟踪错误?
  • 其他?

我用于打开 .pptx 文件的 PowerPoint 版本

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

我的控制台项目如下所示

<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>

我的主程序看起来像这样

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

我的源代码如下所示

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
C# openxml-sdk presentationml

评论

1赞 tomjebo 11/11/2023
与 Word 或 Excel 包相比,PowerPoint 包对生成起始幻灯片的要求更高。可以做的一件事是在 Visual Studio 中安装 Open XML SDK 代码段扩展,并将其 CreatePresentation 代码段与 Open XML SDK PowerPoint Utils 项(具有用于生成包的帮助程序实用工具函数的 .cs 文件)一起使用。即使您不直接在最终代码中使用它,您也会看到从头开始构建 PowerPoint 包所需的内容。
1赞 BateTech 11/13/2023
手动创建相同的 PowerPoint,运行代码以创建 PowerPoint,将两个 pptx 文件重命名为 .zip 文件,然后将两者进行比较。这将提供一些关于缺少什么的提示。
0赞 Emanuele 11/15/2023
不幸的是,您似乎缺少一些层次结构。这个Microsoft代码正在工作,通过引用 learn.microsoft.com/en-us/office/open-xml/...
0赞 GoWiser 11/18/2023
@tomjebo我使用了这些片段,演示文稿结果是空白的。

答:

2赞 borealis-c 11/15/2023 #1

OpenOffice PPT 问题很有趣,我正在尝试使用一些示例代码,并获得了以下工作示例来使用 .NET 6 和 DocumentFormat.OpenXml 2.20(与您相同的版本)创建 powerpoint。

您需要有相当多的层次结构才能让 Powerpoint 毫无怨言地打开文件,即使某些元素没有显示在视觉对象中(如母版幻灯片、调色板等)。删除一个部分将导致 Powerpoint 尝试(成功)修复演示文稿,它只是以编程方式在压缩的 XML 中再次添加该部分。

我没有详细调试您的代码,但我尝试过并且可以重现您的问题。也许这篇文章中的代码示例对您有所帮助:您可以将其用作模板,然后只需将自定义布局添加到相应的幻灯片布局部分即可。玩得愉快!

    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;

    namespace PowerpointWithOpenXmlDemo;

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

    public static class OpenXMLBuilderDemo
    {
        public static void CreatePresentation(string filepath)
        {
            using var presentationDocument = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation);

            var presentationPart = presentationDocument.AddPresentationPart();
            presentationPart.Presentation = new P.Presentation();

            CreateSlide(presentationPart);

            presentationPart.Presentation.Save();
        }

        private static void CreateSlide(PresentationPart presentationPart)
        {
            var slideMasterIdList1 = new P.SlideMasterIdList(new P.SlideMasterId
                { Id = (UInt32Value)2147483648U, RelationshipId = "rId1" });
            var slideIdList1 = new P.SlideIdList(new P.SlideId { Id = (UInt32Value)256U, RelationshipId = "rId2" });
            var slideSize1 = new P.SlideSize { Cx = 9144000, Cy = 6858000, Type = P.SlideSizeValues.Screen4x3 };
            var notesSize1 = new P.NotesSize { Cx = 6858000, Cy = 9144000 };
            var defaultTextStyle1 = new P.DefaultTextStyle();

            presentationPart.Presentation.Append(slideMasterIdList1, slideIdList1, slideSize1, notesSize1,
                defaultTextStyle1);

            var slidePart1 = CreateSlidePart(presentationPart);
            var slideLayoutPart1 = CreateSlideLayoutPart(slidePart1);
            var slideMasterPart1 = CreateSlideMasterPart(slideLayoutPart1);
            var themePart1 = CreateTheme(slideMasterPart1);

            slideMasterPart1.AddPart(slideLayoutPart1, "rId1");
            presentationPart.AddPart(slideMasterPart1, "rId1");
            presentationPart.AddPart(themePart1, "rId5");
        }

        private static SlidePart CreateSlidePart(PresentationPart presentationPart)
        {
            var slidePart1 = presentationPart.AddNewPart<SlidePart>("rId2");
            slidePart1.Slide = new P.Slide(
                new P.CommonSlideData(
                    new P.ShapeTree(
                        new P.NonVisualGroupShapeProperties(
                            new P.NonVisualDrawingProperties { Id = (UInt32Value)1U, Name = "" },
                            new P.NonVisualGroupShapeDrawingProperties(),
                            new P.ApplicationNonVisualDrawingProperties()),
                        new P.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 P.ApplicationNonVisualDrawingProperties(new P.PlaceholderShape())),
                            new P.ShapeProperties(),
                            new P.TextBody(
                                new D.BodyProperties(),
                                new D.ListStyle(),
                                new D.Paragraph(new D.EndParagraphRunProperties { Language = "en-US" }))))),
                new P.ColorMapOverride(new D.MasterColorMapping()));
            return slidePart1;
        }

        private static SlideLayoutPart CreateSlideLayoutPart(SlidePart slidePart1)
        {
            var slideLayoutPart1 = slidePart1.AddNewPart<SlideLayoutPart>("rId1");
            var slideLayout = new P.SlideLayout(
                new P.CommonSlideData(new P.ShapeTree(
                    new P.NonVisualGroupShapeProperties(
                        new P.NonVisualDrawingProperties { Id = (UInt32Value)1U, Name = "" },
                        new P.NonVisualGroupShapeDrawingProperties(),
                        new P.ApplicationNonVisualDrawingProperties()),
                    new P.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 P.ApplicationNonVisualDrawingProperties(new P.PlaceholderShape())),
                        new P.ShapeProperties(),
                        new P.TextBody(
                            new D.BodyProperties(),
                            new D.ListStyle(),
                            new D.Paragraph(new D.EndParagraphRunProperties()))))),
                new P.ColorMapOverride(new D.MasterColorMapping()));
            slideLayoutPart1.SlideLayout = slideLayout;
            return slideLayoutPart1;
        }

        private static SlideMasterPart CreateSlideMasterPart(SlideLayoutPart slideLayoutPart1)
        {
            var slideMasterPart1 = slideLayoutPart1.AddNewPart<SlideMasterPart>("rId1");
            var slideMaster = new P.SlideMaster(
                new P.CommonSlideData(new P.ShapeTree(
                    new P.NonVisualGroupShapeProperties(
                        new P.NonVisualDrawingProperties { Id = (UInt32Value)1U, Name = "" },
                        new P.NonVisualGroupShapeDrawingProperties(),
                        new P.ApplicationNonVisualDrawingProperties()),
                    new P.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 P.ApplicationNonVisualDrawingProperties(new P.PlaceholderShape
                                { Type = P.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 P.SlideLayoutIdList(new P.SlideLayoutId { Id = (UInt32Value)2147483649U, RelationshipId = "rId1" }),
                new P.TextStyles(new P.TitleStyle(), new P.BodyStyle(), new P.OtherStyle()));
            slideMasterPart1.SlideMaster = slideMaster;

            return slideMasterPart1;
        }

        private static ThemePart CreateTheme(SlideMasterPart slideMasterPart1)
        {
            var themePart1 = slideMasterPart1.AddNewPart<ThemePart>("rId5");
            var theme1 = new D.Theme { Name = "Office Theme" };

            var 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;
        }
    }
2赞 Emanuele 11/16/2023 #2

我能够创建一个类似于您的起点(创建一个演示文稿并向其添加一个表格)。 代码不是超级简单也不是很短,但我无法减少它。 尽管如此,它还是会生成一个新的 powerpoint,第一页有一个表格!

Microsoft DOCMicrosoft 示例所采用的代码

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;
        }
    }
}