You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用.NET的Open XML SDK在新建docx中添加指定参数的矩形等形状

使用Open XML SDK在Word文档中添加指定样式的矩形形状

首先确保已安装DocumentFormat.OpenXml NuGet包,这是操作Open XML文档的核心依赖。

以下是完整的代码示例,实现创建新Word文档,并在指定X/Y坐标位置添加红色填充、指定宽高的矩形:

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;

class Program
{
    static void Main(string[] args)
    {
        // 生成Word文档路径
        string docPath = "SampleDocument.docx";

        // 创建新的Word文档
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(docPath, WordprocessingDocumentType.Document))
        {
            // 添加主文档部分
            MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
            mainPart.Document = new Document();
            Body body = mainPart.Document.AppendChild(new Body());
            Paragraph para = body.AppendChild(new Paragraph());
            Run run = para.AppendChild(new Run());

            // 定义矩形的位置(X/Y坐标,单位:EMU)和尺寸(宽/高,单位:EMU)
            // 转换参考:1厘米 = 360000 EMU,1英寸 = 914400 EMU
            long xPos = CentimetersToEmu(2); // X坐标:2厘米
            long yPos = CentimetersToEmu(3); // Y坐标:3厘米
            long width = CentimetersToEmu(4); // 宽度:4厘米
            long height = CentimetersToEmu(2); // 高度:2厘米

            // 创建Drawing元素,用于承载形状
            DW.Drawing drawing = new DW.Drawing();

            // 定义Inline元素,设置形状的位置和环绕方式
            DW.Inline inline = new DW.Inline(
                new DW.Extent() { Cx = width, Cy = height },
                new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
                new DW.DocProperties() { Id = (UInt32Value)1U, Name = "Rectangle 1" },
                new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true }),
                new A.Graphic(
                    new A.GraphicData(
                        new A.ShapeTree(
                            new A.NonVisualGroupShapeProperties(
                                new A.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Group 1" },
                                new A.NonVisualGroupShapeDrawingProperties()),
                            new A.GroupShapeProperties(new A.TransformGroup()),
                            new A.Shape(
                                new A.NonVisualShapeProperties(
                                    new A.NonVisualDrawingProperties() { Id = (UInt32Value)3U, Name = "Rectangle" },
                                    new A.NonVisualShapeDrawingProperties(new A.ShapeLocks() { NoGrouping = true })),
                                new A.ShapeProperties(
                                    new A.Transform2D(
                                        new A.Offset() { X = xPos, Y = yPos },
                                        new A.Extents() { Cx = width, Cy = height }),
                                    new A.SolidFill(new A.RgbColorModelHex() { Val = "FF0000" }), // 红色填充
                                    new A.Outline(
                                        new A.NoFill())), // 去掉边框,如需边框可修改为SolidFill并设置颜色
                                new A.TextBody(
                                    new A.BodyProperties(),
                                    new A.ListStyle(),
                                    new A.Paragraph(new A.EndParagraphRunProperties()))
                            )
                        )
                    ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/shape" }
                )
            )
            {
                DistanceFromTop = 0L,
                DistanceFromBottom = 0L,
                DistanceFromLeft = 0L,
                DistanceFromRight = 0L,
                EditId = "50D07946"
            };

            drawing.Append(inline);
            run.Append(drawing);

            // 保存文档
            mainPart.Document.Save();
        }
    }

    // 辅助方法:厘米转EMU单位
    private static long CentimetersToEmu(double centimeters)
    {
        return (long)(centimeters * 360000);
    }
}

关键代码说明

  • 单位转换:Open XML文档中所有坐标和尺寸使用EMU(English Metric Unit)作为单位,代码中提供了CentimetersToEmu方法方便转换,你也可以根据需求实现英寸转EMU的方法。
  • 形状样式:通过A.SolidFill设置红色填充(RGB值FF0000),如果需要保留边框,可将A.NoFill替换为A.SolidFill并指定边框颜色。
  • 形状位置与尺寸:通过A.Offset设置X/Y坐标,A.Extents设置宽高,对应的值均为EMU单位。
  • 形状类型:代码中默认创建矩形,若需其他基础形状,可在A.Shape中添加A.PresetGeometry元素指定,例如:
    new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeValues.Ellipse }
    
    即可创建椭圆形状。

内容的提问来源于stack exchange,提问作者Vishal Tanawade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 08:05:17