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

Chaknith related to Cómo crear y editar gráficos de Excel en C#
Chaknith Bin
17 de octubre, 2023
Actualizado 10 de diciembre, 2024
Compartir:
This article was translated from English: Does it need improvement?
Translated
View the article in English

En Excel, un gráfico es una representación gráfica de datos. Es una herramienta visual utilizada para mostrar y analizar datos de forma más comprensible y significativa. Excel proporciona una gran variedad de tipos de gráficos, como gráficos de barras, de líneas, circulares, etc., cada uno de los cuales es adecuado para distintos tipos de datos y análisis.

IronXL admite gráficos de columnas, de dispersión, de líneas, circulares, de barras y de áreas con nombres de series, posiciones de leyendas, títulos de gráficos y posiciones de gráficos configurables.


Comienza con IronXL

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

Primer Paso:
green arrow pointer


Crear gráficos Ejemplo

IronXL admite gráficos de columnas, de dispersión, de líneas, circulares, de barras y de áreas. Para crear un gráfico tenemos que especificar algunas cosas por separado.

  1. Comience utilizando el método CreateChart para especificar el tipo de gráfico y las ubicaciones en la hoja de trabajo.

  2. Agregue la serie con el método AddSeries. Este método también acepta una sola columna de datos, ya que es suficiente para algunos tipos de gráficos. El primer parámetro representa el valor del eje horizontal. El segundo parámetro representa el valor para el eje vertical.

  3. Opcionalmente, especifique el nombre de la serie, el nombre del gráfico y la posición de la leyenda.

  4. Invoca el método Plot para trazar el gráfico. El método trazará el gráfico utilizando todos los datos añadidos. Si se llama varias veces a este método, se trazan varios gráficos en lugar de modificar el gráfico existente.

    Vamos a crear algunos gráficos a partir de los datos en el archivo Excel chart.xlsx. A continuación se muestra una vista previa de los datos:

    Datos

Gráfico de columnas

: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
Gráfico de columnas

Gráfico lineal

Dado que un gráfico de líneas puede representar tanta información como un gráfico de columnas, pasar de uno a otro es muy sencillo. Sólo tiene que cambiar el tipo de gráfico.

: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
Gráfico lineal

Gráfico circular

Para un gráfico circular, sólo se necesita una columna de datos.

: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
Gráfico circular

Editar gráfico Ejemplo

Hay algunas cosas que puede editar en el gráfico existente. Puede editar la posición de la leyenda y el título del gráfico. Para editar el gráfico, primero debe recuperar el gráfico accediendo a la propiedad Charts y seleccionando el gráfico deseado para editar. Desde ahí, accede a las propiedades del gráfico para realizar tus ediciones.

: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
En

Eliminar ejemplo de gráfico

Para eliminar un gráfico existente de una hoja de cálculo, primero recupere el gráfico de la propiedad Charts del objeto worksheet. Recibirá una lista de gráficos de la propiedad Gráficos. Pase el objeto de gráfico objetivo al método RemoveChart para eliminarlo.

: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
Chaknith related to Eliminar ejemplo de gráfico
Ingeniero de software
Chaknith es el Sherlock Holmes de los desarrolladores. La primera vez que se le ocurrió que podría tener futuro en la ingeniería de software fue cuando hacía retos de código por diversión. Su trabajo se centra en IronXL e IronBarcode, pero se enorgullece de ayudar a los clientes con todos los productos. Chaknith aprovecha sus conocimientos, adquiridos hablando directamente con los clientes, para ayudar a mejorar los propios productos. Sus comentarios anecdóticos van más allá de los tickets de Jira y apoyan el desarrollo de productos, la documentación y el marketing, para mejorar la experiencia general del cliente.Cuando no está en la oficina, se le puede encontrar aprendiendo sobre aprendizaje automático, codificación y senderismo.