How to add Oval shape to Excel chart using XlsIO?
14 Jul 20254 minutes to read
The following code snippets illustrate how to add Oval shape to Excel chart in C# (cross-platform and Windows-specific) and VB.NET.
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Add chart to worksheet
IChart chart = worksheet.Charts.Add();
//Add oval shape to chart
IShape shape = chart.Shapes.AddAutoShapes(AutoShapeType.Oval, 20, 60, 500, 400);
//Format the shape
shape.Line.ForeColorIndex = ExcelKnownColors.Red;
//Add the text to the oval shape and set the text alignment on the shape
shape.TextFrame.TextRange.Text = "This is an oval shape";
shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;
shape.TextFrame.HorizontalAlignment = ExcelHorizontalAlignment.CenterMiddle;
#region Save
//Saving the workbook
FileStream outputStream = new FileStream(Path.GetFullPath("Output.xlsx"), FileMode.Create, FileAccess.Write);
workbook.SaveAs(outputStream);
#endregion
//Dispose streams
outputStream.Dispose();
}
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Add chart to worksheet
IChart chart = worksheet.Charts.Add();
//Add oval shape to chart
IShape shape = chart.Shapes.AddAutoShapes(AutoShapeType.Oval, 20, 60, 500, 400);
//Format the shape
shape.Line.ForeColorIndex = ExcelKnownColors.Red;
//Add the text to the oval shape and set the text alignment on the shape
shape.TextFrame.TextRange.Text = "This is an oval shape";
shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;
shape.TextFrame.HorizontalAlignment = ExcelHorizontalAlignment.CenterMiddle;
workbook.SaveAs("Output.xlsx");
}
Using excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Xlsx
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Add chart to worksheet
Dim chart As IChart = worksheet.Charts.Add()
'Add oval shape to chart
Dim shape As IShape = chart.Shapes.AddAutoShapes(AutoShapeType.Oval, 20, 60, 500, 400)
'Format the shape
shape.Line.ForeColorIndex = ExcelKnownColors.Red
'Add the text to the oval shape and set the text alignment on the shape
shape.TextFrame.TextRange.Text = "This is an oval shape"
shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered
shape.TextFrame.HorizontalAlignment = ExcelHorizontalAlignment.CenterMiddle
workbook.SaveAs("Output.xlsx")
End Using
A complete working example to add Oval shape to Excel chart using C# is present on this GitHub page.