如何使用 C# 更改 Excel 中的系列颜色?
我用 C# 编写了一个程序,它会自动从 CSV 文件生成一个图表,并将其放入新的 XLS 文件中。但是,我需要将线条的颜色(因为它是折线图)更改为红色而不是默认的蓝色。
我发现这很难做到,而且我在网上找到的东西也不起作用。请问有人可以告诉我该怎么做吗?
I have written a program in C# whereby it automatically generates a graph for me from a CSV file and puts it onto a new XLS file. However, I need to change the color of the Line (as it is a Line Chart) to red rather than the default blue.
I am finding this extremely difficult to do and the stuff I've found online has not worked. Please can someone tell me how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个例子。我注意到当我尝试传递一个整数时,字节似乎是以相反的顺序读取的。因此,分配
0xFF0000
会使颜色变为蓝色,0x0000FF
将线条变为红色。幸运的是微软提供了一个枚举。Here is an example. I noticed when I tried to pass an integer that the bytes seem to be read in reverse order. So assigning
0xFF0000
makes the color blue and0x0000FF
turns the line red. Fortunately Microsoft provided an enumeration.大多数此类问题来自于无法找到需要更改的确切对象和属性。
获取此信息的可靠方法是打开 Excel 文件并转到折线图。开始录制宏,然后更改您要更改的项目。停止录制宏,并查看它生成的代码。这将为您提供必须使用的确切对象和属性。
然后,您可以确保您的 C# 代码使用正确的对象和属性语法。
Most of these type of problems come from not being able to find the exact object and property that needs to be changed.
A sure way to get to this information is to open your Excel file and go to the line chart. Start recording a macro, then change the item that you want to change. Stop recording the macro, and look at the code it generated. This will give you the exact object and property that must be used.
You can then make sure that your C# code is using the correct object and property syntax.
要更改线系列的颜色,您可以使用边框属性:
也可以通过图表图例更改颜色。
要更改线条的颜色:
要更改条形的颜色:
To change the color of a line series, you can use the border property:
The colors can also be changed via the chart legend.
To change the color of a line:
To change the color of a bar:
录制宏绝对不是找到答案的“可靠”方法。对于我来说,Excel 2007 中的图表记录除了一长串“ActiveSheet.ChartObjects("Chart 1").Activate”之外什么也没有给我。上面(或我搜索时其他地方)的答案都不适合我;但是,我能够更改线条粗细和文本并更改标记。
我在更改颜色时遇到的问题是,当我制作新图表或添加新系列时,颜色默认为“自动”。显然,为了关闭此行为,您需要将 Line.Visible 属性设置为 msoTriStateMixed。如果我将 Visible 更改回 msoTrue,则线条将返回其原始颜色,并且在“格式数据系列”、“线条样式”属性下再次选中“自动”。此代码在 Excel 2007 中适用于我:
Recording a macro is definitely not a "sure" way to find the answer. For me in Excel 2007 with my chart recording gives me nothing except a long list of "ActiveSheet.ChartObjects("Chart 1").Activate". None of the answers above (or elsewhere when I searched) worked for me; however, I was able to change line thickness and text and change the markers.
The problem I was having with changing color is that the color is defaulting to Automatic for me when I make a new chart or add a new series. In order to turn off this behavior apparently you need to set the Line.Visible property to msoTriStateMixed. If I change Visible back to msoTrue, then the lines go back to their original color, and the "Automatic" is checked under Format Data Series, Line Style properties again. This code works for me in Excel 2007: