Cómo utilizar C# para crear gráficos de Excel

Chaknith Bin
Chaknith Bin
22 de diciembre, 2020
Actualizado 20 de octubre, 2024
Compartir:
This article was translated from English: Does it need improvement?
Translated
View the article in English

El siguiente How-To le permite crear un gráfico de Excel mediante programación en C# utilizando IronXL.


How to Create Excel Chart in C#

  1. Instale la biblioteca de Excel para crear gráficos de Excel.

  2. Cargue el archivo de Excel existente en un objeto Workbook.

  3. Crea un gráfico con CreateChart.

  4. Establecer el título y la leyenda del gráfico

  5. Llama al método Plot.

  6. Guarda el Workbook en el archivo de Excel.

    Primer paso

1. Instalar IronXL

En primer lugar, la forma más fácil de instalar IronXL es hacer uso del gestor de paquetes NuGet en Visual Studio:

  • Seleccione el menú Proyecto
  • Gestión de paquetes NuGet
  • Buscar IronXL.Excel
  • Instale

    También puede introducir el siguiente comando en el símbolo del sistema del desarrollador:

Install-Package IronXL.Excel

O descargar desde aquí: https://ironsoftware.com/csharp/excel/packages/IronXL.zip


Tutorial

2. Crear Gráfico Excel para .NET

¡Ahora para el proyecto!

Añade los siguientes datos en una hoja de cálculo Excel. Se muestra a continuación:

Datos que se utilizarán para el gráfico

Figure 1Data to be used for charting

Agregue los Namespaces necesarios para trabajar con gráficos de Excel en IronXL.

using IronXL;
using IronXL.Drawing.Charts;
using IronXL;
using IronXL.Drawing.Charts;
Imports IronXL
Imports IronXL.Drawing.Charts
$vbLabelText   $csharpLabel

Añadir código para crear el gráfico de Excel mediante programación con IronXL:

private void button1_Click(object sender, EventArgs e)
{
    WorkBook wb = WorkBook.Load("Chart_Ex.xlsx");
    WorkSheet ws = wb.DefaultWorkSheet;

    var chart = ws.CreateChart(ChartType.Column, 10, 15, 25, 20);

    const string xAxis = "A2:A7";

    var series = chart.AddSeries(xAxis, "B2:B7");
    series.Title = ws ["B1"].StringValue;

    series = chart.AddSeries(xAxis, "C2:C7");
    series.Title = ws ["C1"].StringValue;

    series = chart.AddSeries(xAxis, "D2:D7");
    series.Title = ws ["D1"].StringValue;

    chart.SetTitle("Column Chart");
    chart.SetLegendPosition(LegendPosition.Bottom);
    chart.Plot();
    wb.SaveAs("Exported_Column_Chart.xlsx");
}
private void button1_Click(object sender, EventArgs e)
{
    WorkBook wb = WorkBook.Load("Chart_Ex.xlsx");
    WorkSheet ws = wb.DefaultWorkSheet;

    var chart = ws.CreateChart(ChartType.Column, 10, 15, 25, 20);

    const string xAxis = "A2:A7";

    var series = chart.AddSeries(xAxis, "B2:B7");
    series.Title = ws ["B1"].StringValue;

    series = chart.AddSeries(xAxis, "C2:C7");
    series.Title = ws ["C1"].StringValue;

    series = chart.AddSeries(xAxis, "D2:D7");
    series.Title = ws ["D1"].StringValue;

    chart.SetTitle("Column Chart");
    chart.SetLegendPosition(LegendPosition.Bottom);
    chart.Plot();
    wb.SaveAs("Exported_Column_Chart.xlsx");
}
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
	Dim wb As WorkBook = WorkBook.Load("Chart_Ex.xlsx")
	Dim ws As WorkSheet = wb.DefaultWorkSheet

	Dim chart = ws.CreateChart(ChartType.Column, 10, 15, 25, 20)

	Const xAxis As String = "A2:A7"

	Dim series = chart.AddSeries(xAxis, "B2:B7")
	series.Title = ws ("B1").StringValue

	series = chart.AddSeries(xAxis, "C2:C7")
	series.Title = ws ("C1").StringValue

	series = chart.AddSeries(xAxis, "D2:D7")
	series.Title = ws ("D1").StringValue

	chart.SetTitle("Column Chart")
	chart.SetLegendPosition(LegendPosition.Bottom)
	chart.Plot()
	wb.SaveAs("Exported_Column_Chart.xlsx")
End Sub
$vbLabelText   $csharpLabel

Se crean un objeto Libro de trabajo y un objeto Hoja de trabajo. El método CreateChart del objeto Worksheet se llama para especificar el tipo de gráfico y la ubicación del gráfico. Se añade la serie del gráfico, con su Título y la Leyenda. Se muestra a continuación.

Salida de gráficos

Figura 2Salida del gráfico


Acceso rápido a la biblioteca

Documentación de referencia de la API IronXL

Learn more and share how to merge, unmerge, and work with cells in Excel spreadsheets using the handy Documentación de referencia de la API IronXL.

Documentación de referencia de la API IronXL
Documentation related to 2. Crear Gráfico Excel para .NET
Chaknith Bin
Ingeniero de software
Chaknith trabaja en IronXL e IronBarcode. Tiene una gran experiencia en C# y .NET, ayudando a mejorar el software y a apoyar a los clientes. Sus conocimientos de las interacciones con los usuarios contribuyen a mejorar los productos, la documentación y la experiencia general.