News Category

How to change the color of data series in an Excel chart

2016-11-24 07:40:20 Written by  support iceblue
Rate this item
(0 votes)

Spire.XLS enables developers to change the color of data series in an Excel chart with just a few lines of code. Once changed, the legend color will also turn into the same as the color you set to the series.

The following part demonstrates the steps of how to accomplish this task. Below picture shows the original colors of the data series in an Excel chart:

How to change the color of data series in an Excel chart

Code snippets:

Step 1: Instantiate a Workbook object and load the Excel workbook.

Workbook book = new Workbook();
book.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet.

Worksheet sheet = book.Worksheets[0];

Step 3: Get the second series of the chart.

ChartSerie cs = sheet.Charts[0].Series[1];

Step 4: Change the color of the second series to Purple.

cs.Format.Fill.FillType = ShapeFillType.SolidColor;
cs.Format.Fill.ForeColor = Color.FromKnownColor(KnownColor.Purple);

Step 5: Save the Excel workbook to file.

book.SaveToFile("ChangeSeriesColor.xlsx", ExcelVersion.Version2010);

After running the code, the color of the second series has been changed into Purple, screenshot as shown below.

How to change the color of data series in an Excel chart

Full code:

[C#]
using System.Drawing;
using Spire.Xls;
using Spire.Xls.Charts;

namespace Change_Series_Color
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook book = new Workbook();
            book.LoadFromFile("Sample.xlsx");
            Worksheet sheet = book.Worksheets[0];
            ChartSerie cs = sheet.Charts[0].Series[1];
            cs.Format.Fill.FillType = ShapeFillType.SolidColor;
            cs.Format.Fill.ForeColor = Color.FromKnownColor(KnownColor.Purple);
            book.SaveToFile("ChangeSeriesColor.xlsx", ExcelVersion.Version2010);
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Xls
Imports Spire.Xls.Charts

Namespace Change_Series_Color
	Class Program
		Private Shared Sub Main(args As String())
			Dim book As New Workbook()
			book.LoadFromFile("Sample.xlsx")
			Dim sheet As Worksheet = book.Worksheets(0)
			Dim cs As ChartSerie = sheet.Charts(0).Series(1)
			cs.Format.Fill.FillType = ShapeFillType.SolidColor
			cs.Format.Fill.ForeColor = Color.FromKnownColor(KnownColor.Purple)
			book.SaveToFile("ChangeSeriesColor.xlsx", ExcelVersion.Version2010)
		End Sub
	End Class
End Namespace

Additional Info

  • tutorial_title: Change the color of data series in an Excel chart
Last modified on Monday, 06 September 2021 02:15