学习C#调用OpenXml操作word文档的基本用法(31:学习图形类-1)

  文本运行类Run的子类型Drawing用于保存word文档中的图片、图表、形状等图形对象,命名空间为DocumentFormat.OpenXml.Wordprocessing,对应document.xml文件内的元素如下图所示。本文学习使用Drawing类将图片保存到Word文档的基本用法。

  图形类Drawing的类继承链为OpenXmlElement ->
OpenXmlCompositeElement-> Drawing,其主要属性包括以下两个:
  1)Anchor属性:浮动式布局,精确控制图形在页面上的绝对位置,并可选择是否随文字移动;
  2)Inline属性:嵌入式布局,将图形视为一个大的文本字符,跟随文字流排列,并影响行高。
  以嵌入式布局为例,将参考文献5中的图片作为配图插入word文档的末尾,示例代码及运行效果如下所示:

csharp 复制代码
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(sfd.FileName, WordprocessingDocumentType.Document))
{
    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
    mainPart.Document = new Document();
    Body body = mainPart.Document.AppendChild(new Body());

    Paragraph paragraph = body.AppendChild(new Paragraph());
    Run run = paragraph.AppendChild(new Run());

    for (int i = 0; i < txtContent.Lines.Length; i++)
    {
        Text text = new Text();
        text.Space = SpaceProcessingModeValues.Preserve;
        text.Text = txtContent.Lines[i];
        run.AppendChild(text);

        run.Append(new Break());
    }

    run.Append(new Text("----------------------------------日期:"));

    if (rbShortDate.Checked)
    {
        run.Append(new YearShort());
        run.Append(new Text("-"));
        run.Append(new MonthShort());
        run.Append(new Text("-"));
        run.Append(new DayShort());
    }

    if (rbLongDate.Checked)
    {
        run.Append(new YearLong());
        run.Append(new Text("-"));
        run.Append(new MonthLong());
        run.Append(new Text("-"));
        run.Append(new DayLong());
    }

    run.Append(new Break());

    ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
    using (FileStream stream = new FileStream(picImage.Tag as string, FileMode.Open,FileAccess.Read))
    {
        imagePart.FeedData(stream);
    }
    string relationshipId = mainPart.GetIdOfPart(imagePart);

    Drawing drawing = CreateImageDrawing(relationshipId);
    run.Append(drawing);               
}

public Drawing CreateImageDrawing(string relationshipId)
{
    return new Drawing(
     new DW.Inline(
         new DW.Extent() { Cx = 990000L, Cy = 792000L },
         new DW.EffectExtent()
         {
             LeftEdge = 0L,
             TopEdge = 0L,
             RightEdge = 0L,
             BottomEdge = 0L
         },
         new DW.DocProperties()
         {
             Id = (UInt32Value)1U,
             Name = "Picture 1"
         },
         new DW.NonVisualGraphicFrameDrawingProperties(
             new A.GraphicFrameLocks() { NoChangeAspect = true }),
         new A.Graphic(
             new A.GraphicData(
                 new PIC.Picture(
                     new PIC.NonVisualPictureProperties(
                         new PIC.NonVisualDrawingProperties()
                         {
                             Id = (UInt32Value)0U,
                             Name = "New Bitmap Image.jpg"
                         },
                         new PIC.NonVisualPictureDrawingProperties()),
                     new PIC.BlipFill(
                         new A.Blip(
                             new A.BlipExtensionList(
                                 new A.BlipExtension()
                                 {
                                     Uri =
                                        "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                 })
                         )
                         {
                             Embed = relationshipId,
                             CompressionState =
                             A.BlipCompressionValues.Print
                         },
                         new A.Stretch(
                             new A.FillRectangle())),
                     new PIC.ShapeProperties(
                         new A.Transform2D(
                             new A.Offset() { X = 0L, Y = 0L },
                             new A.Extents() { Cx = 990000L, Cy = 792000L }),
                         new A.PresetGeometry(
                             new A.AdjustValueList()
                         )
                         { Preset = A.ShapeTypeValues.Rectangle }))
             )
             { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
     )
     {
         DistanceFromTop = (UInt32Value)0U,
         DistanceFromBottom = (UInt32Value)0U,
         DistanceFromLeft = (UInt32Value)0U,
         DistanceFromRight = (UInt32Value)0U,
         EditId = "50D07946"
     });
}

参考文献

1https://github.com/dotnet/Open-XML-SDK

2https://learn.microsoft.com/zh-cn/office/open-xml/open-xml-sdk

3https://learn.microsoft.com/zh-cn/dotnet/api/documentformat.openxml.wordprocessing.style?view=openxml-3.0.1

4https://blog.csdn.net/i042416/article/details/126228816

5https://baike.baidu.com/item/静夜思/214

相关推荐
DS随心转小程序18 小时前
文心文字怎么转为 word?告别繁琐排版操作,AI 导出鸭一站式完成文档转换工作
人工智能·word·豆包·deepseek·ai导出鸭
风华圆舞20 小时前
HarmonyOS 自定义绘制实战 —— 用 ArkGraphics2D 画一个会卷曲翻动的页面网格
harmonyos·arkts·drawing·drawvertices·翻页卷曲·有限差分法线
AI导出鸭2 天前
怎么让千问做表格?AI导出鸭苹果版将千问输出的管道表格智能解析为二维结构,一键导出为Excel或Word标准表格。
人工智能·chatgpt·word·excel·ai导出鸭
zyplayer-doc2 天前
zyplayer-doc企业知识库能做什么:从文档创建、权限管理到AI问答的完整能力
大数据·javascript·数据库·人工智能·pdf·word
zyplayer-doc3 天前
企业文档改错或误删后怎么办:zyplayer-doc编辑历史、版本回滚和回收站怎么用
大数据·开发语言·javascript·数据库·pdf·word
Ai-_Man4 天前
豆包智能体内容批量导出:哪些该存、存成什么、怎么存v
人工智能·ai·小程序·word
weixin_416660074 天前
解决方案:DeepSeek不支持直接导出Word
word
2601_965912915 天前
PDF转Word工具深度横评:2026年国内免费方案技术对比
pdf·word
L歪歪君 山水甲天5 天前
Office文件的奥秘——.NET平台下不借助Office实现Word、Powerpoint等文件的解析(1)
word·powerpoint·.net
SpaceAIGlobal5 天前
Word文档一键转PPT?4种方法实测对比与选型分析(2026)
word·powerpoint