有人知道如何在 C# 中设置 PowerPoint 2010 饼图的切片/图例的颜色吗?我无法使我从 MSDN 网站上读到的任何内容发挥作用。我无法找出获取正确对象和属性的正确方法。
编辑: 好吧,我考虑过添加代码,但我所拥有的代码不起作用,所以我不确定它会有多大帮助或提供多少信息。我无法弄清楚使用哪个对象/方法/属性来访问饼图切片颜色。我尝试过 Point、LegendKey、LegendEntry、Legend 以及每个的相关方法/属性。我已经尝试了许多甚至不再在我的代码中表示的事情。
但是,就其值(value)而言,这就是我现在的代码:
PowerPoint.Series series = (PowerPoint.Series)xlChart.SeriesCollection(1);
PowerPoint.Point point = (PowerPoint.Point)series.Points(xlCol);
point.Interior.ColorIndex = Convert.ToInt32(dataArray[2, i]);
PowerPoint.Legend legend = (PowerPoint.Legend)xlChart.Legend;
PowerPoint.LegendEntry lentry = (PowerPoint.LegendEntry)legend.LegendEntries(1);
最佳答案
Interior.ColorIndex
不起作用,因为枚举中只有两个值:xlColorIndexAutomatic
和 xlColorIndexNone
。
不过,你已经很接近了。你想要的是Interior.Color
。我使用十六进制来设置颜色,但我确信还有其他方法。下面的示例基于这样的假设:存在一个现有 PowerPoint 文件,第一张幻灯片上有一个饼图,没有其他内容。显然,您会根据自己的情况进行调整。
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
namespace SampleApp
{
class Program
{
static void Main(string[] args)
{
var filePath = @"C:\users\userx\desktop\test.pptx";
var app = new PowerPoint.Application();
var presentation = app.Presentations.Open(filePath);
var slide = presentation.Slides[1];
var chart = slide.Shapes[1].Chart;
var series = chart.SeriesCollection(1) as PowerPoint.Series;
var point = series.Points(1) as PowerPoint.Point;
point.Interior.Color = 0x41BA5D;
point = series.Points(2) as PowerPoint.Point;
point.Interior.Color = 0xA841BA;
point = series.Points(3) as PowerPoint.Point;
point.Interior.Color = 0xBA4141;
point = series.Points(4) as PowerPoint.Point;
point.Interior.Color = 0x7AB4FF;
}
}
}
原始饼图如下所示:
虽然新图表的外观如下:
正如我所提到的,设置颜色的方法有很多种,我向您展示了十六进制方式。如果您引用System.Drawing
程序集,那么您将可以访问Color
,这大大简化了事情:
var point = series.Points(1) as PowerPoint.Point;
point.Interior.Color = Color.Red;
point = series.Points(2) as PowerPoint.Point;
point.Interior.Color = Color.Pink;
point = series.Points(3) as PowerPoint.Point;
point.Interior.Color = Color.Black;
point = series.Points(4) as PowerPoint.Point;
point.Interior.Color = Color.Green;
图例条目将相应地更改其颜色,因此如果您使用这种方法,您甚至不必担心在那里设置颜色。
正如您所知,互操作可能很痛苦。希望这能为您解决一些问题。
关于c# - 设置饼图切片和图例的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35851592/