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

  使用图形类Drawing不仅可以将图片保存到word文档,还能将图表、表格等数据保存到word文档,关键就在于其子类型GraphicData支持关联多种类型的图形数据,本文记录以嵌入式布局方式向word中插入图表的基本用法。

  主要代码如下所示:

csharp 复制代码
using A = DocumentFormat.OpenXml.Drawing;
using C=DocumentFormat.OpenXml.Drawing.Charts;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;

if(cbInsertChart.Checked)
{
    ChartPart chartPart = mainPart.AddNewPart<ChartPart>();
    string chartPartId = mainPart.GetIdOfPart(chartPart);

    Drawing drawing = CreateChartDrawing(chartPartId, chartPart);
    run.Append(drawing);
}

public Drawing CreateChartDrawing(string relationshipId, ChartPart chartPart)
{
    var chartSpace = new C.ChartSpace();
    chartSpace.AddNamespaceDeclaration("c", "http://schemas.openxmlformats.org/drawingml/2006/chart");
    chartSpace.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
    chartSpace.AppendChild(new C.EditingLanguage { Val = "zh-CN" });

    var chart = new C.Chart();
    chart.AppendChild(new C.AutoTitleDeleted { Val = true });

    var plotArea = new C.PlotArea();

    var barChart = new C.BarChart(
        new C.BarDirection { Val = C.BarDirectionValues.Column },
        new C.BarGrouping { Val = C.BarGroupingValues.Clustered },
        new C.VaryColors { Val = true }
    );

    var series = new C.BarChartSeries(
        new C.Index { Val = 0 },
        new C.Order { Val = 0 },
        new C.SeriesText(new C.NumericValue("测试数据"))
    );

    series.AppendChild(new C.CategoryAxisData(
        new C.StringLiteral(
            new C.PointCount { Val = 4 },
            new C.StringPoint { Index = 0, NumericValue = new C.NumericValue("A") },
            new C.StringPoint { Index = 1, NumericValue = new C.NumericValue("B") },
            new C.StringPoint { Index = 2, NumericValue = new C.NumericValue("C") },
            new C.StringPoint { Index = 3, NumericValue = new C.NumericValue("D") }
        )
    ));

    series.AppendChild(new C.Values(
        new C.NumberLiteral(
            new C.PointCount { Val = 4 },
            new C.NumericPoint { Index = 0, NumericValue = new C.NumericValue("10") },
            new C.NumericPoint { Index = 1, NumericValue = new C.NumericValue("20") },
            new C.NumericPoint { Index = 2, NumericValue = new C.NumericValue("30") },
            new C.NumericPoint { Index = 3, NumericValue = new C.NumericValue("40") }
        )
    ));

    barChart.AppendChild(series);

    // 坐标轴
    var catAxis = new C.CategoryAxis(
        new C.AxisId { Val = 100 },
        new C.Scaling(new C.Orientation { Val = C.OrientationValues.MinMax }),
        new C.AxisPosition { Val = C.AxisPositionValues.Bottom },
        new C.CrossingAxis { Val = 200 },
        new C.Crosses { Val = C.CrossesValues.AutoZero },
        new C.TickLabelPosition { Val = C.TickLabelPositionValues.NextTo }
    );

    var valAxis = new C.ValueAxis(
        new C.AxisId { Val = 200 },
        new C.Scaling(new C.Orientation { Val = C.OrientationValues.MinMax }),
        new C.AxisPosition { Val = C.AxisPositionValues.Left },
        new C.CrossingAxis { Val = 100 },
        new C.Crosses { Val = C.CrossesValues.AutoZero },
        new C.TickLabelPosition { Val = C.TickLabelPositionValues.NextTo },
        new C.MajorTickMark { Val = C.TickMarkValues.None },
        new C.MinorTickMark { Val = C.TickMarkValues.None }
    );

    // 让BarChart引用坐标轴ID
    barChart.AppendChild(new C.AxisId { Val = 100 });
    barChart.AppendChild(new C.AxisId { Val = 200 });

    plotArea.Append(barChart, catAxis, valAxis);
    chart.Append(plotArea);

    chartSpace.AppendChild(chart);
    chartSpace.Save(chartPart);

    return new Drawing(
        new DW.Inline(
            new DW.Extent { Cx = 6000000, Cy = 4000000 },
            new DW.EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
            new DW.DocProperties { Id = 1, Name = "Chart 1" },
            new DW.NonVisualGraphicFrameDrawingProperties(
                new A.GraphicFrameLocks { NoChangeAspect = true }
            ),
            new A.Graphic(
                new A.GraphicData(
                    new C.ChartReference { Id = relationshipId }
                )
                { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" }
            )
        )
    );
}

  下面的截图是程序运行效果及word文档的内容截图。

参考文献

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

相关推荐
qq_546937272 天前
Excel批量转PDF_Word_图片,支持自动合并报表,效率翻倍。
pdf·word·excel
(Charon)3 天前
【C++ 面试高频:内存管理、RAII 和智能指针详解】
java·开发语言·word
江畔柳前堤3 天前
github实战指南03-Pull Request 全流程实战
开发语言·人工智能·python·深度学习·github·word
2603_954138394 天前
PDF 转 Word 工具深度评测:从参数解析到实战避坑
pdf·word
知南x4 天前
【DPDK例程学习】(4) l2fwd
学习·word
江畔柳前堤4 天前
github实战指南00-命令在哪里执行?
人工智能·线性代数·oracle·数据挖掘·github·word
江畔柳前堤4 天前
github实战指南05-Fork与开源协作
人工智能·线性代数·oracle·开源·github·word
yivifu5 天前
怎样将Word文档中脚注引用后面的空格轻松删除
word·vba
Sour5 天前
Word 文档翻译后保留格式的检查清单:标题、表格、图片、目录和批注
pdf·word·办公软件·office·文档翻译
qq_422152576 天前
Word 文件太大怎么压缩?2026 年文档瘦身方案对比
开发语言·c#·word