使用OpenXML操作PPT公共方法总结

推荐一个ppt模板操作工具: https://github.com/tkrotoff/PptxTemplater

然后进入正题...

 

一 拷贝一个幻灯片

  1 private static long SLIDE_ID = 1000;
  2 private static uint UNIQUE_ID = 0;
  3 
  4 /// <summary>
  5 /// 拷贝一个幻灯片
  6 /// </summary>
  7 /// <param name="destPresentationPart"></param>
  8 /// <param name="slidePartTemplate"></param>
  9 /// <param name="offsetToLast"></param>
 10 /// <returns></returns>
 11 public static SlidePart CloneSlidePart(PresentationPart destPresentationPart, SlidePart slidePartTemplate, int? offsetToLast = 2)
 12 {
 13     int? insertAt = null;
 14     if (offsetToLast != null)
 15     {
 16         insertAt = destPresentationPart.SlideParts.Count() - offsetToLast.Value;
 17     }
 18 
 19     // If the merged presentation does not have a SlideIdList 
 20     // element yet, add it.
 21     if (destPresentationPart.Presentation.SlideIdList == null)
 22     {
 23         destPresentationPart.Presentation.SlideIdList = new SlideIdList();
 24     }
 25 
 26     // Get unique ids for the slide master and slide lists
 27     // for use later.
 28     UNIQUE_ID = GetMaxSlideMasterId(destPresentationPart.Presentation.SlideMasterIdList);
 29 
 30     uint maxSlideId = GetMaxSlideId(destPresentationPart.Presentation.SlideIdList);
 31     SlidePart destSp;
 32     SlideMasterPart destMasterPart;
 33     string relId;
 34     SlideMasterId newSlideMasterId;
 35     SlideId newSlideId;
 36 
 37     // Add the slide part to the destination presentation.
 38     relId = "slide" + (SLIDE_ID++);
 39     destSp = destPresentationPart.AddPart<SlidePart>(slidePartTemplate, relId);
 40 
 41     // The slide master part was added. Make sure the
 42     // relationship between the main presentation part and
 43     // the slide master part is in place.
 44     destMasterPart = destSp.SlideLayoutPart.SlideMasterPart;
 45     destPresentationPart.AddPart(destMasterPart);
 46 
 47     // Add the slide master id to the slide master id list.
 48     UNIQUE_ID++;
 49     newSlideMasterId = new SlideMasterId();
 50     newSlideMasterId.RelationshipId = destPresentationPart.GetIdOfPart(destMasterPart);
 51     newSlideMasterId.Id = UNIQUE_ID;
 52     destPresentationPart.Presentation.SlideMasterIdList.Append(newSlideMasterId);
 53 
 54     // Add the slide id to the slide id list.
 55     maxSlideId++;
 56     newSlideId = new SlideId();
 57     newSlideId.RelationshipId = relId;
 58     newSlideId.Id = maxSlideId;
 59     if (insertAt != null)
 60     {
 61         destPresentationPart.Presentation.SlideIdList.InsertAt(newSlideId, insertAt.Value);
 62     }
 63     else
 64     {
 65         destPresentationPart.Presentation.SlideIdList.Append(newSlideId);
 66     }
 67 
 68     // Make sure that all slide layout ids are unique.
 69     FixSlideLayoutIds(destPresentationPart);
 70 
 71     // Save the changes to the destination deck.
 72     destPresentationPart.Presentation.Save();
 73 
 74     return destSp;
 75 }
 76 
 77 /// <summary>
 78 /// FixSlideLayoutIds
 79 /// </summary>
 80 /// <param name="presPart"></param>
 81 private static void FixSlideLayoutIds(PresentationPart presPart)
 82 {
 83     // Make sure that all slide layouts have unique ids.2020/6/20
 84     foreach (SlideMasterPart slideMasterPart in
 85       presPart.SlideMasterParts)
 86     {
 87         foreach (SlideLayoutId slideLayoutId in
 88           slideMasterPart.SlideMaster.SlideLayoutIdList)
 89         {
 90             UNIQUE_ID++;
 91             slideLayoutId.Id = (uint)UNIQUE_ID;
 92         }
 93 
 94         slideMasterPart.SlideMaster.Save();
 95     }
 96 }
 97 
 98 /// <summary>
 99 /// GetMaxSlideId
100 /// </summary>
101 /// <param name="slideIdList"></param>
102 /// <returns></returns>
103 private static uint GetMaxSlideId(SlideIdList slideIdList)
104 {
105     // Slide identifiers have a minimum value of greater than or
106     // equal to 256 and a maximum value of less than 2147483648. 
107     uint max = 256;
108 
109     if (slideIdList != null)
110         // Get the maximum id value from the current set of children.
111         foreach (SlideId child in slideIdList.Elements<SlideId>())
112         {
113             uint id = child.Id;
114 
115             if (id > max)
116                 max = id;
117         }
118 
119     return max;
120 }
121 
122 /// <summary>
123 /// GetMaxSlideMasterId
124 /// </summary>
125 /// <param name="slideMasterIdList"></param>
126 /// <returns></returns>
127 private static uint GetMaxSlideMasterId(SlideMasterIdList slideMasterIdList)
128 {
129     // Slide master identifiers have a minimum value of greater than
130     // or equal to 2147483648. 
131     uint max = 2147483648;
132 
133     if (slideMasterIdList != null)
134         // Get the maximum id value from the current set of children.
135         foreach (SlideMasterId child in
136           slideMasterIdList.Elements<SlideMasterId>())
137         {
138             uint id = child.Id;
139 
140             if (id > max)
141                 max = id;
142         }
143 
144     return max;
145 }
View Code

 

二 表格中创建文本单元格

  1 using D = DocumentFormat.OpenXml.Drawing;
  2 
  3 /// <summary>
  4 /// 创建文本单元格
  5 /// </summary>
  6 /// <param name="text"></param>
  7 /// <returns></returns>
  8 public static D.TableCell CreateTextCell(string text, int? tableRowIndex, int fontSize = 12, string borderLineHexColor = "1784C7")
  9 {
 10     var textCol = new string[2];
 11     if (!string.IsNullOrEmpty(text))
 12     {
 13         if (text.Length > 25)
 14         {
 15             textCol[0] = text.Substring(0, 25);
 16             textCol[1] = text.Substring(26);
 17         }
 18         else
 19         {
 20             textCol[0] = text;
 21         }
 22     }
 23     else
 24     {
 25         textCol[0] = string.Empty;
 26     }
 27 
 28     var tableCell = new D.TableCell();
 29     var textBody = new D.TextBody();
 30     var bodyProperties = new D.BodyProperties();
 31     var listStyle = new D.ListStyle();
 32 
 33     textBody.Append(bodyProperties);
 34     textBody.Append(listStyle);
 35 
 36     var nonNull = textCol.Where(t => t != null).ToList();
 37     foreach (var textVal in nonNull)
 38     {
 39         var paragraph = new D.Paragraph();
 40         var paragraphProperties = new D.ParagraphProperties()
 41         {
 42             Alignment = D.TextAlignmentTypeValues.Center,  //水平居中
 43         };
 44 
 45         var run = new D.Run();
 46         var runProperties = new D.RunProperties()
 47         {
 48             Language = "en-US",
 49             Dirty = false,
 50             //SmtClean = false,
 51             FontSize = fontSize * 100,  //字体大小
 52         };
 53         //设置字体颜色
 54         //D.SolidFill solidFill = new D.SolidFill();
 55         //D.RgbColorModelHex rgbColorModelHex = new D.RgbColorModelHex() { Val = "0070C0" };
 56         //solidFill.Append(rgbColorModelHex);
 57         //runProperties.Append(solidFill);
 58         // 设置文本
 59         var drawingText = new D.Text()
 60         {
 61             Text = textVal,
 62         };
 63 
 64         run.Append(runProperties);
 65         run.Append(drawingText);
 66         paragraph.Append(paragraphProperties);
 67         paragraph.Append(run);
 68         textBody.Append(paragraph);
 69     }
 70 
 71     var tableCellProperties = new D.TableCellProperties()
 72     {
 73         Anchor = D.TextAnchoringTypeValues.Center,   //垂直居中
 74     };
 75     //设置单元格边框属性(线型,线宽,颜色等)
 76     SetTableCellBorderLineProperties(tableCellProperties, D.PresetLineDashValues.Dot, D.CompoundLineValues.Single, 2000, borderLineHexColor);
 77     //设置单元格填充属性
 78     if (tableRowIndex != null)
 79     {
 80         string tableCellFillColor = (tableRowIndex.Value % 2 == 0) ? "FFFFFF" : "F2F2F2";
 81         var tableCellSolidFill = new D.SolidFill()
 82         {
 83             RgbColorModelHex = new D.RgbColorModelHex() { Val = tableCellFillColor }
 84         };
 85         tableCellProperties.Append(tableCellSolidFill);
 86     }
 87 
 88     tableCell.Append(textBody);
 89     tableCell.Append(tableCellProperties);
 90     return tableCell;
 91 }
 92 
 93 /// <summary>
 94 /// SetTableCellBorderLineProperties
 95 /// </summary>
 96 /// <param name="tableCellProperties"></param>
 97 /// <param name="presetLineDashValues"></param>
 98 /// <param name="lineType"></param>
 99 /// <param name="lineHexColor"></param>
100 private static void SetTableCellBorderLineProperties(D.TableCellProperties tableCellProperties, D.PresetLineDashValues presetLineDashValues, D.CompoundLineValues lineType, int lineWidth, string lineHexColor)
101 {
102     //left border
103     var leftBorderLineProperties = new D.LeftBorderLineProperties() { CompoundLineType = lineType, Width = lineWidth };
104     var solidFillL = new D.SolidFill() { RgbColorModelHex = new D.RgbColorModelHex() { Val = lineHexColor } };
105     var presetDashL = new D.PresetDash() { Val = presetLineDashValues };
106     leftBorderLineProperties.Append(solidFillL);
107     leftBorderLineProperties.Append(presetDashL);
108     tableCellProperties.Append(leftBorderLineProperties);
109     //right border
110     var rightBorderLineProperties = new D.RightBorderLineProperties() { CompoundLineType = lineType, Width = lineWidth };
111     var solidFillR = new D.SolidFill() { RgbColorModelHex = new D.RgbColorModelHex() { Val = lineHexColor } };
112     var presetDashR = new D.PresetDash() { Val = presetLineDashValues };
113     rightBorderLineProperties.Append(solidFillR);
114     rightBorderLineProperties.Append(presetDashR);
115     tableCellProperties.Append(rightBorderLineProperties);
116     //top border
117     var topBorderLineProperties = new D.TopBorderLineProperties() { CompoundLineType = lineType, Width = lineWidth };
118     var solidFillT = new D.SolidFill() { RgbColorModelHex = new D.RgbColorModelHex() { Val = lineHexColor } };
119     var presetDashT = new D.PresetDash() { Val = presetLineDashValues };
120     topBorderLineProperties.Append(solidFillT);
121     topBorderLineProperties.Append(presetDashT);
122     tableCellProperties.Append(topBorderLineProperties);
123     //bottom border
124     var bottomBorderLineProperties = new D.BottomBorderLineProperties() { CompoundLineType = lineType, Width = lineWidth };
125     var solidFillB = new D.SolidFill() { RgbColorModelHex = new D.RgbColorModelHex() { Val = lineHexColor } };
126     var presetDashB = new D.PresetDash() { Val = presetLineDashValues };
127     bottomBorderLineProperties.Append(solidFillB);
128     bottomBorderLineProperties.Append(presetDashB);
129     tableCellProperties.Append(bottomBorderLineProperties);
130 }
View Code

 

三 ppt幻灯片添加图片

 1 /// <summary>
 2 /// 添加图片
 3 /// </summary>
 4 /// <param name="slidePart">slidePart</param>
 5 /// <param name="imageBytes">imageBytes</param>
 6 /// <param name="offsetX">X轴偏移</param>
 7 /// <param name="offsetY">Y轴偏移</param>
 8 /// <param name="sizeX">X轴尺寸</param>
 9 /// <param name="sizeY">Y轴尺寸</param>
10 public static void AddImage(SlidePart slidePart, byte[] imageBytes, long offsetX, long offsetY, long sizeX, long sizeY)
11 {
12     var imagePart = slidePart.AddImagePart(ImagePartType.Png);
13     using (var memoryStream = new MemoryStream(imageBytes))
14     {
15         imagePart.FeedData(memoryStream);
16     }
17     var tree = slidePart
18         .Slide
19         .Descendants<DocumentFormat.OpenXml.Presentation.ShapeTree>()
20         .First();
21 
22     var picture = new DocumentFormat.OpenXml.Presentation.Picture();
23     picture.NonVisualPictureProperties = new DocumentFormat.OpenXml.Presentation.NonVisualPictureProperties();
24     picture.NonVisualPictureProperties.Append(new DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties
25     {
26         Name = "My Shape",
27         Id = (UInt32)tree.ChildElements.Count - 1
28     });
29 
30     var nonVisualPictureDrawingProperties = new DocumentFormat.OpenXml.Presentation.NonVisualPictureDrawingProperties();
31     nonVisualPictureDrawingProperties.Append(new DocumentFormat.OpenXml.Drawing.PictureLocks()
32     {
33         NoChangeAspect = true
34     });
35     picture.NonVisualPictureProperties.Append(nonVisualPictureDrawingProperties);
36     picture.NonVisualPictureProperties.Append(new DocumentFormat.OpenXml.Presentation.ApplicationNonVisualDrawingProperties());
37 
38     var blipFill = new DocumentFormat.OpenXml.Presentation.BlipFill();
39     var blip1 = new DocumentFormat.OpenXml.Drawing.Blip()
40     {
41         Embed = slidePart.GetIdOfPart(imagePart)
42     };
43     var blipExtensionList1 = new DocumentFormat.OpenXml.Drawing.BlipExtensionList();
44     var blipExtension1 = new DocumentFormat.OpenXml.Drawing.BlipExtension()
45     {
46         Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
47     };
48     var useLocalDpi1 = new DocumentFormat.OpenXml.Office2010.Drawing.UseLocalDpi()
49     {
50         Val = false
51     };
52     useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
53     blipExtension1.Append(useLocalDpi1);
54     blipExtensionList1.Append(blipExtension1);
55     blip1.Append(blipExtensionList1);
56     var stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
57     stretch.Append(new DocumentFormat.OpenXml.Drawing.FillRectangle());
58     blipFill.Append(blip1);
59     blipFill.Append(stretch);
60     picture.Append(blipFill);
61 
62     picture.ShapeProperties = new DocumentFormat.OpenXml.Presentation.ShapeProperties();
63     picture.ShapeProperties.Transform2D = new DocumentFormat.OpenXml.Drawing.Transform2D();
64     picture.ShapeProperties.Transform2D.Append(new DocumentFormat.OpenXml.Drawing.Offset
65     {
66         X = offsetX,
67         Y = offsetY,
68     });
69     picture.ShapeProperties.Transform2D.Append(new DocumentFormat.OpenXml.Drawing.Extents
70     {
71         Cx = sizeX,
72         Cy = sizeY,
73     });
74     picture.ShapeProperties.Append(new DocumentFormat.OpenXml.Drawing.PresetGeometry
75     {
76         Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle
77     });
78 
79     tree.Append(picture);
80 }
View Code
posted @ 2020-06-20 16:39  秒杀5S  阅读(1702)  评论(0编辑  收藏  举报