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

如何使用C# Office Interop Word库结合MS Graph插入SVG矢量图表到Word

使用Office Interop Word插入带矢量属性图表的实现方案

核心逻辑说明

你当前使用的MSGraph.Chart.8OLE对象生成的图表本身就支持矢量渲染,结合SVG矢量数据有两种实现路径:将SVG解析出的数值作为图表数据源生成原生矢量图表,或是直接将SVG作为矢量图表元素插入Word文档。

实现步骤

  1. 读取SVG矢量数据
  • 可通过System.Xml.Linq原生API或Svg.NET等类库解析SVG文件中的坐标、数值、路径等矢量属性,不需要转换为位图,保留全部矢量信息
  • 若仅需将完整SVG作为矢量图表插入,不需要解析属性,直接保留SVG文件路径即可
  1. 完整代码实现
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;

// 此处省略你已有的Word.Application、Word.Document对象初始化逻辑
object oMissing = Missing.Value;
object oEndOfDoc = "\\endofdoc";
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

// ========== 方案1:将SVG解析出的数值作为数据源,生成MSGraph矢量图表 ==========
object oClassType = "MSGraph.Chart.8";
Word.InlineShape oleShape = wrdRng.InlineShapes.AddOLEObject(
    ref oClassType, ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing
);
object oChart = oleShape.OLEFormat.Object;
object oChartApp = oChart.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, oChart, null);

// 将从SVG解析得到的数值写入MSGraph关联数据表
object dataSheet = oChart.GetType().InvokeMember("DataSheet", BindingFlags.GetProperty, null, oChart, null);
// 示例:写入第一行第一列数据,可根据解析到的SVG数据批量写入
object[] writeParam = new object[3] { 1, 1, "你从SVG解析到的对应数值" };
dataSheet.GetType().InvokeMember("Cells", BindingFlags.SetProperty, null, dataSheet, writeParam);

// 刷新图表,设置尺寸,此时生成的图表原生为矢量格式,缩放不会模糊
oChartApp.GetType().InvokeMember("Update", BindingFlags.InvokeMethod, null, oChartApp, null);
oChartApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, oChartApp, null);
oleShape.Width = oWord.InchesToPoints(6.25f);
oleShape.Height = oWord.InchesToPoints(3.57f);

// ========== 方案2:直接插入SVG作为矢量图表(支持Office 2016及以上版本) ==========
object svgPath = @"C:\你的SVG文件路径\chart.svg";
Word.InlineShape svgShape = wrdRng.InlineShapes.AddPicture2(
    ref svgPath, ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing
);
svgShape.Width = oWord.InchesToPoints(6.25f);
svgShape.Height = oWord.InchesToPoints(3.57f);

注意事项

  • 若需要兼容Office 2013及更早版本,可将SVG转换为EMF矢量格式后插入,EMF为Office全版本原生支持的矢量格式,不会丢失缩放属性
  • 不要将SVG转换为PNG、JPG等位图格式插入,否则会丢失矢量属性,放大后会出现模糊
  • MSGraph生成的图表本身为矢量渲染,只要写入的数据源正确,导出PDF、打印等场景都会保留矢量效果

内容的提问来源于stack exchange,提问作者alpha wolf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:18:02