How to: Apply Gradient Fill
- 3 minutes to read
You can specify a gradient fill of a cell’s background color if the Fill.BackgroundColor has an empty value (default).
To specify a gradient fill for an individual cell, modify the Formatting.Fill properties of the Cell object. These properties are inherited from the Formatting interface.
To specify a gradient fill for a range of cells, call the CellRange.BeginUpdateFormatting method for this range, use the Fill property of the returned Formatting object to specify the gradient fill, and call the CellRange.EndUpdateFormatting method to finalize the modification.
The Formatting.Fill property returns the Fill object. Set the Fill.FillType to the FillType.Gradient value. Use the Fill.Gradient property to access the object with a GradientFill interface, which allows you to specify gradient characteristics.
To share gradient settings with multiple cells in a single step, create or modify a style with the Formatting.Fill properties specified as required, and assign this style to CellRange.Style for the desired cells.
This example demonstrates how to fill a cell background with a color gradient of the linear type. Use the Formatting.Fill property to access the Fill object that specifies the background fill of a cell or a range. Specify the Fill.FillType to the FillType.Gradient type and specify the gradient characteristics - tilt and two color stops. Only two color stops with positions of 0 and 1 are currently supported.
// Specify a linear gradient fill for a cell.
Fill fillA1 = worksheet.Cells["A1"].Fill;
fillA1.FillType = FillType.Gradient;
fillA1.Gradient.Type = GradientFillType.Linear;
// Set the tilt for the gradient line in degrees.
// 90 degree angle defines a color transition from the top to the bottom.
fillA1.Gradient.Degree = 90;
// Specify two gradient colors.
// The position of a color stop should be either 0 (start) or 1 (end).
fillA1.Gradient.Stops.Add(0, Color.Yellow);
fillA1.Gradient.Stops.Add(1, Color.SkyBlue);
// Specify a linear gradient fill for a range.
worksheet.Range["C3:F8"].Fill.FillType = FillType.Gradient;
GradientFill rangeGradient1 = worksheet.Range["C3:F8"].Fill.Gradient;
rangeGradient1.Type = GradientFillType.Linear;
// Set the tilt for the gradient line in degrees.
// 45 degree angle defines a color transition from top left to bottom right.
rangeGradient1.Degree = 45;
// Specify two gradient colors.
// The position of a color stop should be either 0 (start) or 1 (end).
GradientStopCollection rangeStops1 = rangeGradient1.Stops;
rangeStops1.Add(0, Color.BlanchedAlmond);
rangeStops1.Add(1, Color.Blue);