我正在尝试使用 Visual Studio 在
C#
中使用 Open XML SDK
创建 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
吗?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
OpenOffice PPT 问题很有趣,我尝试了一些示例代码,并获得了以下工作示例,以使用 .NET 6 和 DocumentFormat.OpenXml 2.20(与您相同的版本)创建一个 powerpoint。
即使 Powerpoint 没有显示在视觉效果中(例如母版幻灯片、调色板等),您也需要提供相当多的层次结构,才能毫无怨言地打开它。删除一个部分将导致 Powerpoint 尝试(成功)修复演示文稿,这只是以编程方式再次添加该部分。
我没有调试您上面的代码,只是尝试了一下,可以重现您的问题。也许这篇文章中的代码可以帮助您:您可以使用它作为模板,然后只需将自定义布局添加到相应的幻灯片布局部分。玩得开心!
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
namespace PowerpointFix;
using P = DocumentFormat.OpenXml.Presentation;
using D = DocumentFormat.OpenXml.Drawing;
public static class OpenXMLBuilderToolbox
{
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;
}
}