Cómo crear y editar gráficos de Excel en C#

How to Create and Edit Excel Charts in C#

This article was translated from English: Does it need improvement?
Translated
View the article in English

In Excel, a chart is a graphical representation of data. It is a visual tool used to display and analyze data in a more understandable and meaningful way. Excel provides a variety of chart types, such as bar charts, line charts, pie charts, and more, each of which is suited for different types of data and analysis.

Quickstart: Create and Plot a Line Chart in Seconds

With IronXL, you can install, load a workbook, call CreateChart, add your data series, set your title & legend position, and Plot—all in just a few lines. This example shows how quickly you can go from no chart to a polished visual using native C# methods—without any Interop overhead.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronXL with NuGet Package Manager

    PM > Install-Package IronXL.Excel

  2. Copy and run this code snippet.

    var chart = workSheet.CreateChart(ChartType.Line, 2, 2, 15, 10).AddSeries("A2:A10","B2:B10").Title = workSheet["B1"].StringValue; chart.SetTitle("Quick Line Chart").SetLegendPosition(LegendPosition.Bottom).Plot();
  3. Deploy to test on your live environment

    Start using IronXL in your project today with a free trial
    arrow pointer


Get started with IronXL

Comience a usar IronXL en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer


Create Charts Example

IronXL supports column, scatter, line, pie, bar, and area charts. To create a chart, we have to specify a few things separately.

  1. Start by using the CreateChart method to specify the type of chart and its location in the worksheet.
  2. Add the series with the AddSeries method. This method also accepts a single column of data since that is sufficient for some chart types. The first parameter represents values for the horizontal axis. The second parameter represents values for the vertical axis.
  3. Optionally, specify the series name, chart name, and legend position.
  4. Invoke the Plot method to plot the chart. The method will plot the chart using all the data that was added. Multiple calls to this method lead to plotting multiple charts instead of modifying the existing chart.

Let's create some charts from the data in the chart.xlsx Excel file. A preview of the data is displayed below:

Data

Column Chart

:path=/static-assets/excel/content-code-examples/how-to/create-edit-charts-column-chart.cs
using IronXL;
using IronXL.Drawing.Charts;

WorkBook workBook = WorkBook.Load("chart.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set the chart type and position
IChart chart = workSheet.CreateChart(ChartType.Column, 5, 5, 20, 10);

string xAxis = "A2:A7";

// Add the series
IChartSeries series = chart.AddSeries(xAxis, "B2:B7");
series.Title = workSheet["B1"].StringValue;

// Add the series
series = chart.AddSeries(xAxis, "C2:C7");
series.Title = workSheet["C1"].StringValue;

// Add the series
series = chart.AddSeries(xAxis, "D2:D7");
series.Title = workSheet["D1"].StringValue;

// Set the chart title
chart.SetTitle("Column Chart");

// Set the legend position
chart.SetLegendPosition(LegendPosition.Bottom);

// Plot the chart
chart.Plot();

workBook.SaveAs("columnChart.xlsx");
Imports IronXL
Imports IronXL.Drawing.Charts

Private workBook As WorkBook = WorkBook.Load("chart.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Set the chart type and position
Private chart As IChart = workSheet.CreateChart(ChartType.Column, 5, 5, 20, 10)

Private xAxis As String = "A2:A7"

' Add the series
Private series As IChartSeries = chart.AddSeries(xAxis, "B2:B7")
series.Title = workSheet("B1").StringValue

' Add the series
series = chart.AddSeries(xAxis, "C2:C7")
series.Title = workSheet("C1").StringValue

' Add the series
series = chart.AddSeries(xAxis, "D2:D7")
series.Title = workSheet("D1").StringValue

' Set the chart title
chart.SetTitle("Column Chart")

' Set the legend position
chart.SetLegendPosition(LegendPosition.Bottom)

' Plot the chart
chart.Plot()

workBook.SaveAs("columnChart.xlsx")
$vbLabelText   $csharpLabel
Column chart

Line Chart

Since a line chart can represent as much information as a column chart, switching between the two is very simple. You only need to change the chart type.

:path=/static-assets/excel/content-code-examples/how-to/create-edit-charts-line-chart.cs
using IronXL;
using IronXL.Drawing.Charts;

WorkBook workBook = WorkBook.Load("chart.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set the chart type and position
IChart chart = workSheet.CreateChart(ChartType.Column, 5, 5, 20, 10);

string xAxis = "A2:A7";

// Add the series
IChartSeries series = chart.AddSeries(xAxis, "B2:B7");
series.Title = workSheet["B1"].StringValue;

// Add the series
series = chart.AddSeries(xAxis, "C2:C7");
series.Title = workSheet["C1"].StringValue;

// Add the series
series = chart.AddSeries(xAxis, "D2:D7");
series.Title = workSheet["D1"].StringValue;

// Set the chart title
chart.SetTitle("Line Chart");

// Set the legend position
chart.SetLegendPosition(LegendPosition.Bottom);

// Plot the chart
chart.Plot();

workBook.SaveAs("lineChart.xlsx");
Imports IronXL
Imports IronXL.Drawing.Charts

Private workBook As WorkBook = WorkBook.Load("chart.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Set the chart type and position
Private chart As IChart = workSheet.CreateChart(ChartType.Column, 5, 5, 20, 10)

Private xAxis As String = "A2:A7"

' Add the series
Private series As IChartSeries = chart.AddSeries(xAxis, "B2:B7")
series.Title = workSheet("B1").StringValue

' Add the series
series = chart.AddSeries(xAxis, "C2:C7")
series.Title = workSheet("C1").StringValue

' Add the series
series = chart.AddSeries(xAxis, "D2:D7")
series.Title = workSheet("D1").StringValue

' Set the chart title
chart.SetTitle("Line Chart")

' Set the legend position
chart.SetLegendPosition(LegendPosition.Bottom)

' Plot the chart
chart.Plot()

workBook.SaveAs("lineChart.xlsx")
$vbLabelText   $csharpLabel
Line chart

Pie Chart

For a pie chart, only one column of data is needed.

:path=/static-assets/excel/content-code-examples/how-to/create-edit-charts-pie-chart.cs
using IronXL;
using IronXL.Drawing.Charts;

WorkBook workBook = WorkBook.Load("chart.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set the chart type and position
IChart chart = workSheet.CreateChart(ChartType.Pie, 5, 5, 20, 10);

string xAxis = "A2:A7";

// Add the series
IChartSeries series = chart.AddSeries(xAxis, "B2:B7");
series.Title = workSheet["B1"].StringValue;

// Set the chart title
chart.SetTitle("Pie Chart");

// Set the legend position
chart.SetLegendPosition(LegendPosition.Bottom);

// Plot the chart
chart.Plot();

workBook.SaveAs("pieChart.xlsx");
Imports IronXL
Imports IronXL.Drawing.Charts

Private workBook As WorkBook = WorkBook.Load("chart.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Set the chart type and position
Private chart As IChart = workSheet.CreateChart(ChartType.Pie, 5, 5, 20, 10)

Private xAxis As String = "A2:A7"

' Add the series
Private series As IChartSeries = chart.AddSeries(xAxis, "B2:B7")
series.Title = workSheet("B1").StringValue

' Set the chart title
chart.SetTitle("Pie Chart")

' Set the legend position
chart.SetLegendPosition(LegendPosition.Bottom)

' Plot the chart
chart.Plot()

workBook.SaveAs("pieChart.xlsx")
$vbLabelText   $csharpLabel
Pie chart

Edit Chart Example

There are a few things you can edit in an existing chart. You can edit the legend position and chart title. To edit the chart, you must first retrieve the chart by accessing the Charts property and select the targeted chart for editing. From there, access the properties of the chart to make your edits.

:path=/static-assets/excel/content-code-examples/how-to/create-edit-charts-edit-chart.cs
using IronXL;
using IronXL.Drawing.Charts;

WorkBook workBook = WorkBook.Load("pieChart.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Retrieve the chart
IChart chart = workSheet.Charts[0];

// Edit the legend position
chart.SetLegendPosition(LegendPosition.Top);

// Edit the chart title
chart.SetTitle("Edited Chart");

workBook.SaveAs("editedChart.xlsx");
Imports IronXL
Imports IronXL.Drawing.Charts

Private workBook As WorkBook = WorkBook.Load("pieChart.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Retrieve the chart
Private chart As IChart = workSheet.Charts(0)

' Edit the legend position
chart.SetLegendPosition(LegendPosition.Top)

' Edit the chart title
chart.SetTitle("Edited Chart")

workBook.SaveAs("editedChart.xlsx")
$vbLabelText   $csharpLabel
Before
After

Remove Chart Example

To remove an existing chart from a spreadsheet, first retrieve the chart from the Charts property of the worksheet object. You will receive a list of charts from the Charts property. Pass the targeted chart object to the RemoveChart method to remove it.

:path=/static-assets/excel/content-code-examples/how-to/create-edit-charts-remove-chart.cs
using IronXL;
using IronXL.Drawing.Charts;
using System.Collections.Generic;

WorkBook workBook = WorkBook.Load("pieChart.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Retrieve the chart
List<IChart> chart = workSheet.Charts;

// Remove the chart
workSheet.RemoveChart(chart[0]);

workBook.SaveAs("removedChart.xlsx");
Imports IronXL
Imports IronXL.Drawing.Charts
Imports System.Collections.Generic

Private workBook As WorkBook = WorkBook.Load("pieChart.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Retrieve the chart
Private chart As List(Of IChart) = workSheet.Charts

' Remove the chart
workSheet.RemoveChart(chart(0))

workBook.SaveAs("removedChart.xlsx")
$vbLabelText   $csharpLabel

Preguntas Frecuentes

¿Cómo puedo crear gráficos de Excel en C# sin usar Interop?

Puede crear gráficos de Excel en C# sin Interop usando la biblioteca IronXL. Primero, descargue la biblioteca desde NuGet y luego use métodos como CreateChart para especificar el tipo de gráfico y su ubicación en la hoja de trabajo.

¿Qué pasos están involucrados en personalizar gráficos de Excel usando C#?

Para personalizar gráficos de Excel usando C#, primero prepare sus datos, luego use el método AddSeries para agregar series de datos. Personalice las propiedades del gráfico, como los títulos y las posiciones de la leyenda, accediendo al gráfico a través de la propiedad Charts de la hoja de trabajo.

¿Cómo cambio entre diferentes tipos de gráficos en C#?

Cambiar entre diferentes tipos de gráficos en C# es sencillo. Simplemente cambie el parámetro de tipo de gráfico en el método CreateChart para alternar entre gráficos de columnas, dispersión, líneas, pastel, barras o áreas.

¿Cuál es el método para guardar los cambios después de editar un gráfico de Excel en C#?

Después de editar un gráfico de Excel, use el método SaveAs para guardar los cambios en el libro de trabajo, asegurando que todas las modificaciones se conserven.

¿Puedo eliminar un gráfico existente de una hoja de trabajo de Excel usando C#?

Sí, puede eliminar un gráfico existente obteniéndolo a través de la propiedad Charts de la hoja de trabajo y luego usando el método RemoveChart para eliminarlo.

¿Cuáles son los beneficios de usar IronXL para la creación de gráficos en aplicaciones .NET?

IronXL permite una creación y edición eficiente de gráficos en aplicaciones .NET sin depender de Excel Interop, lo que mejora el rendimiento y reduce la complejidad. Soporta varios tipos de gráficos y proporciona métodos para una fácil personalización.

¿Cómo puedo trazar un gráfico en C# después de agregar series de datos?

Después de agregar series de datos usando el método AddSeries, puede trazar el gráfico llamando al método Plot, que genera el gráfico utilizando los datos proporcionados.

¿Es posible editar las propiedades de un gráfico en C# después de que ha sido creado?

Sí, puede editar las propiedades de un gráfico en C# accediendo a él a través de la propiedad Charts de la hoja de trabajo y modificando atributos como el título del gráfico, la posición de la leyenda y más.

Chaknith Bin
Ingeniero de Software
Chaknith trabaja en IronXL e IronBarcode. Tiene un profundo conocimiento en C# y .NET, ayudando a mejorar el software y apoyar a los clientes. Sus conocimientos derivados de las interacciones con los usuarios contribuyen a mejores productos, documentación y experiencia en general.
¿Listo para empezar?
Nuget Descargas 1,686,155 | Versión: 2025.11 recién lanzado