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

标签 c# openxml openxml-sdk presentationml

问题

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

我创建的演示文稿包含一张幻灯片和一张 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 365 MSO 的 Microsoft® PowerPoint®(版本 2310 内部版本 16.0.16924.20054)64 位

我的控制台项目如下所示

<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

最佳答案

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

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

关于c# - 使用 Open XML SDK 在 C# 中创建的演示文稿在打开时已损坏且为空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77459046/

相关文章:

c# - 在 C# 中将 JS 'escape' d 字符串转换回正确的格式

c# - 打开 XML 更改表格的字体大小

list - 如何在c#中使用OpenXml在excel文件的列/列中设置数据验证列表?

c# - 修改excel单元格

c# - 没有临时文件的 OpenXML 文件下载

c# - 如何使用 OpenXML SDK 2.5 生成目录?

c# - 从 LINQ to XML 查询获取单个字符串

c# - 来自 Explorer 的命令行参数在每个空格处拆分

c# - WCF 服务向客户端发送数据

.net - 我可以在Mono中使用Open XML SDK吗?