DEV Community

Allen Yang
Allen Yang

Posted on • Edited on

Create Excel Charts in C# for Efficient Reporting

Create Charts in Excel Using C#

Generating insightful data visualizations is a cornerstone of effective data analysis, and often, these visualizations need to reside within familiar Excel workbooks. For developers, the challenge lies in programmatically creating these charts, especially when dealing with dynamic data or automating report generation. Manually opening Excel and crafting charts is time-consuming and error-prone for repetitive tasks. This tutorial provides a practical solution, demonstrating how to leverage C# and a powerful library to effortlessly create various chart types directly within Excel files, transforming raw data into compelling visual narratives.


Setting Up Your Environment

To programmatically interact with Excel files from a C# application, a dedicated library is essential. While the .NET framework offers some basic file I/O, it lacks native support for the complex structure of Excel workbooks and their charting capabilities. For this tutorial, we will be using Spire.XLS for .NET, a robust and efficient library designed for comprehensive Excel manipulation. It allows developers to create, read, write, and convert Excel files with ease, including advanced features like chart generation.

To install Spire.XLS for .NET, the simplest and recommended method is via NuGet Package Manager in Visual Studio:

  1. Open your project in Visual Studio.
  2. Right-click on your project in the Solution Explorer and select "Manage NuGet Packages...".
  3. In the NuGet Package Manager, go to the "Browse" tab.
  4. Search for Spire.XLS.
  5. Select Spire.XLS from the search results (ensure it's the one from E-iceblue) and click "Install".
  6. Accept any license agreements to complete the installation.

This library simplifies complex Excel operations into intuitive C# objects and methods, making it an excellent choice for automating data visualization tasks.


Fundamental Chart Creation

Let’s start with a basic column chart, one of the most common visualizations for comparing values across categories in Excel.

Example 1: Column Chart

A column chart is ideal for comparing multiple data series across discrete categories such as months, products, or regions.

using Spire.Xls;
using Spire.Xls.Charts;

namespace ExcelChartGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];
            sheet.Name = "Sales Data";

            // Write sample data (including headers)
            sheet.Range["A1"].Text = "Month";
            sheet.Range["B1"].Text = "Revenue";
            sheet.Range["C1"].Text = "Expenses";

            string[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun" };
            double[] revenue = { 25000, 30000, 28000, 35000, 32000, 38000 };
            double[] expenses = { 18000, 20000, 19000, 22000, 21000, 25000 };

            for (int i = 0; i < months.Length; i++)
            {
                sheet.Range[i + 2, 1].Text = months[i];
                sheet.Range[i + 2, 2].NumberValue = revenue[i];
                sheet.Range[i + 2, 3].NumberValue = expenses[i];
            }

            sheet.Range.AutoFitColumns();

            // Add a chart
            Chart chart = sheet.Charts.Add();

            // Position the chart
            chart.LeftColumn = 1;
            chart.TopRow = 9;
            chart.RightColumn = 10;
            chart.BottomRow = 30;

            // Bind data range (headers included)
            chart.DataRange = sheet.Range["A1:C7"];
            chart.SeriesDataFromRange = false;

            // Set chart type
            chart.ChartType = ExcelChartType.ColumnClustered;

            // Set titles
            chart.ChartTitle = "Monthly Revenue vs. Expenses";
            chart.PrimaryCategoryAxis.Title = "Month";
            chart.PrimaryValueAxis.Title = "Amount ($)";

            // Show legend
            chart.HasLegend = true;
            chart.Legend.Position = LegendPositionType.Bottom;

            workbook.SaveToFile("ColumnChart_Example.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output Preview:

Create Column Chart in Excel Using C#

Explanation

  • DataRange includes both headers and data values.
  • Excel automatically generates chart series based on the table structure.

Exploring Other Chart Types

Once you understand the core pattern—prepare data → set DataRange → choose ChartType—you can easily create other chart types.

Example 2: Line Chart

Line charts are best suited for visualizing trends over time.

using Spire.Xls;

namespace ExcelChartGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];
            sheet.Name = "Stock Prices";

            sheet.Range["A1"].Text = "Day";
            sheet.Range["B1"].Text = "Stock A";
            sheet.Range["C1"].Text = "Stock B";

            string[] days = { "Day 1", "Day 2", "Day 3", "Day 4", "Day 5", "Day 6", "Day 7" };
            double[] stockA = { 100.5, 102.1, 101.8, 103.5, 104.2, 103.9, 105.0 };
            double[] stockB = { 98.2, 99.5, 100.1, 99.8, 101.5, 102.0, 101.7 };

            for (int i = 0; i < days.Length; i++)
            {
                sheet.Range[i + 2, 1].Text = days[i];
                sheet.Range[i + 2, 2].NumberValue = stockA[i];
                sheet.Range[i + 2, 3].NumberValue = stockB[i];
            }

            sheet.Range.AutoFitColumns();

            Chart chart = sheet.Charts.Add();
            chart.LeftColumn = 1;
            chart.TopRow = 10;
            chart.RightColumn = 10;
            chart.BottomRow = 26;

            chart.DataRange = sheet.Range["A1:C8"];
            chart.SeriesDataFromRange = false;
            chart.ChartType = ExcelChartType.Line;

            chart.ChartTitle = "Daily Stock Price Trends";
            chart.PrimaryCategoryAxis.Title = "Day";
            chart.PrimaryValueAxis.Title = "Price ($)";

            chart.HasLegend = true;

            workbook.SaveToFile("LineChart_Example.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output Preview:

Create Line Chart in Excel Using C#

Key Difference:
Only the ChartType changes. The data-binding logic remains exactly the same.

Example 3: Pie Chart

A pie chart displays how each category contributes to a whole.

using Spire.Xls;
using Spire.Xls.Charts;

namespace ExcelChartGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];
            sheet.Name = "Market Share";

            sheet.Range["A1"].Text = "Company";
            sheet.Range["B1"].Text = "Share (%)";

            string[] companies = { "Company A", "Company B", "Company C", "Company D", "Others" };
            double[] shares = { 35, 25, 15, 10, 15 };

            for (int i = 0; i < companies.Length; i++)
            {
                sheet.Range[i + 2, 1].Text = companies[i];
                sheet.Range[i + 2, 2].NumberValue = shares[i];
            }

            sheet.Range.AutoFitColumns();

            Chart chart = sheet.Charts.Add();
            chart.LeftColumn = 1;
            chart.TopRow = 9;
            chart.RightColumn = 7;
            chart.BottomRow = 25;

            chart.DataRange = sheet.Range["A1:B7"];
            chart.SeriesDataFromRange = false;
            chart.ChartType = ExcelChartType.Pie;

            chart.ChartTitle = "Market Share Distribution";

            // Display value and percentage
            ChartSerie serie = chart.Series[0];
            serie.DataPoints.DefaultDataPoint.DataLabels.HasValue = true;
            serie.DataPoints.DefaultDataPoint.DataLabels.HasPercentage = true;

            chart.HasLegend = true;

            workbook.SaveToFile("PieChart_Example.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output Preview:

Create Pie Chart in Excel Using C#

Customization and Best Practices

Recommended Practices

  • Prefer DataRange over manual series creation
    Let Excel detect series automatically whenever possible.

  • Include headers in your data range
    Clear headers ensure correct category and series names.

  • Choose the right chart type

    • Column → comparisons
    • Line → trends
    • Pie → proportions
  • Avoid over-customization

    Too many labels, colors, or series can reduce readability.

Conclusion

This tutorial has demonstrated the power and flexibility of using C# with Spire.XLS for .NET to programmatically generate a variety of charts within Excel. We've covered setting up your development environment, creating fundamental chart types like column, line, and pie charts, and explored essential customization options. The ability to automate Excel chart creation empowers developers to build dynamic reporting tools, integrate data visualization into larger applications, and streamline workflows that previously relied on manual intervention. By leveraging these techniques, you can transform raw data into visually compelling and easily digestible insights, enhancing data analysis and communication within your applications. We encourage you to explore the extensive documentation of Spire.XLS for .NET to discover even more chart types and advanced customization features.

Top comments (0)