Skip to main content Skip to footer

Programmatically Generate Excel XLSX Files using C# and a .NET Excel API Library

Quick Start Guide
Tutorial Concept

Learn how to generate Excel spreadsheets in code using C# and a .NET Excel API library. Create workbooks and worksheets, populate ranges with data, build tables, apply formulas and styling, add conditional formatting, generate pivot tables, create charts, and save everything to an XLSX file without requiring Microsoft Excel.

What You Will Need .NET 8 or higher, and the DS.Documents.Excel NuGet package.
Controls Referenced

Document Solutions for Excel .NET API

Documentation | Demos

Creating Excel files programmatically is a common requirement in modern business applications. From financial reports to operational dashboards, spreadsheets remain one of the most widely used formats for sharing and analyzing structured data.

When developers need to generate Excel documents in code, they often want more than just raw data export. Real-world spreadsheets usually require formatting, formulas, tables, pivot tables, and charts to make the data useful and presentation-ready.

Document Solutions for Excel .NET (DsExcel .NET) enables developers to generate and modify Excel spreadsheets entirely in code, without requiring Microsoft Excel to be installed. This makes it well suited for automated reporting, server-side spreadsheet generation, and cross-platform .NET applications.

Using DsExcel .NET, developers can create complete workbooks with multiple worksheets, structured tables, formulas, styling, pivot tables, and charts in a fully programmatic workflow.

In this tutorial, you will learn how to generate a three-sheet Excel workbook using C# and .NET by building a simple budgeting and reporting workbook that includes tables, formulas, a pivot table, and a chart.

Download a free trial of Document Solutions for Excel and start automating your formula parsing workflows today.


.NET Developer Guide to Programmatically Generating Excel Spreadsheets Using C#

  1. Generate Excel Spreadsheets in C# with .NET
  2. What You Will Need
  3. What You Will Build
  4. Create the C# Workbook
  5. Example Scenario: Building a Multi-Sheet Excel Report
    1. Step 1: Initialize the Workbook and First Worksheet
    2. Step 2: Add Data to the Worksheet
    3. Step 3: Create Excel Tables
    4. Step 4: Add Formulas and Named Ranges
    5. Step 5: Apply Styles and Formatting
    6. Step 6: Add Conditional Formatting
    7. Step 7: Create a Pivot Table
    8. Step 8: Add a Chart
    9. Step 9: Save the Excel File
  6. Summary

Generate Excel Spreadsheets in C# with .NET

Developers often need to generate Excel spreadsheets programmatically when building reporting systems, exporting business data, or automating spreadsheet creation in .NET applications.

Using Document Solutions for Excel .NET, applications can:

  • Create Excel workbooks and worksheets in C#
  • Populate ranges with raw or external data
  • Build Excel tables programmatically
  • Add formulas and named ranges
  • Apply styling and formatting
  • Generate pivot tables in code
  • Create charts in .NET
  • Save workbooks to XLSX without Excel dependencies

Instead of relying on Microsoft Excel automation, DsExcel .NET provides a fully managed API for building rich spreadsheet documents directly in code. To explore these workbook generation capabilities in more detail, review the Document Solutions for Excel .NET documentation and sample demos.


What You Will Need

Before beginning this tutorial, make sure you have the following installed:

  • Visual Studio 2022 or later
  • .NET 8 SDK or later
  • Document Solutions for Excel .NET (DsExcel .NET)

Install the NuGet package:

Install-Package DS.Documents.Excel

The examples in this tutorial use the core Excel API namespace:

using GrapeCity.Documents.Excel;
using System.Drawing;

What You Will Build

In this tutorial, we will build a three-sheet Excel workbook that includes:

  • A worksheet containing two formatted tables for income and expenses
  • Workbook formulas and named ranges for summary calculations
  • Conditional formatting for visual emphasis
  • A pivot table worksheet for summarizing product sales data
  • A chart worksheet for visualizing quarterly sales changes

This example demonstrates how to create a practical workbook layout that combines spreadsheet structure, calculation logic, data summarization, and visualization.


Create the C# Workbook

Start by creating a .NET console application and importing the required namespaces.

using System;
using GrapeCity.Documents.Excel;
using System.Drawing;

Next, define the program entry point.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Excel generation demo.");
    }
}

Example Scenario: Building a Multi-Sheet Excel Report

In this tutorial, we will build a simple Excel reporting workbook with three worksheets:

  • A Tables sheet that tracks monthly income and expenses
  • A Pivot Table sheet that summarizes sales data by category, product, amount, and country
  • A Chart sheet that visualizes quarterly sales changes across regions

Follow along with the steps below to see this in action.

Step 1: Initialize the Workbook and First Worksheet

Start by creating a new workbook and renaming the default worksheet.

// Create a new workbook.
Workbook workbook = new Workbook();

// Get the first worksheet.
IWorksheet worksheet = workbook.Worksheets[0];
workbook.Worksheets[0].Name = "Tables";

At this point, the workbook contains a single worksheet named Tables, which will be used for the budgeting portion of the report. For more information on creating workbooks and managing worksheets, see the DsExcel .NET documentation for Workbooks and Worksheets.

Step 2: Add Data to the Worksheet

To populate spreadsheet content efficiently, use a two-dimensional object[,] array and assign it directly to a range.

In real-world applications, the data could come from a database, API, CRM system, or other external source.

For example, if you are working with a DataTable, you can load the data into an array and write it to the worksheet in one operation.

object[,] data = new object[rowCount, columnCount];

for (int row = 0; row < rowCount; row++)
for (int column = 0; column < columnCount; column++)
    data[row, column] = dataTable.Rows[row][column];

worksheet.Range[row, column, rowCount, columnCount].Value = data;

For this tutorial, we will use hard-coded sample data for the income and expense sections.

// Create data for the first table.
worksheet.Range["B3:C7"].Value = new object[,]
{
    { "ITEM", "AMOUNT" },
    { "Income 1", 2500 },
    { "Income 2", 1000 },
    { "Income 3", 250 },
    { "Other", 250 },
};

// Create data for the second table.
worksheet.Range["B10:C23"].Value = new object[,]
{
    { "ITEM", "AMOUNT" },
    { "Rent/mortgage", 800 },
    { "Electricity", 120 },
    { "Gas", 50 },
    { "Cell phone", 45 },
    { "Groceries", 500 },
    { "Car payment", 273 },
    { "Auto expenses", 120 },
    { "Student loans", 50 },
    { "Credit cards", 100 },
    { "Auto Insurance", 78 },
    { "Personal care", 50 },
    { "Entertainment", 100 },
    { "Miscellaneous", 50 },
};

Next, add labels that will be used in the summary section of the worksheet.

worksheet.Range["B2:C2"].Merge();
worksheet.Range["B2"].Value = "MONTHLY INCOME";
worksheet.Range["B9:C9"].Merge();
worksheet.Range["B9"].Value = "MONTHLY EXPENSES";
worksheet.Range["E2:G2"].Merge();
worksheet.Range["E2"].Value = "PERCENTAGE OF INCOME SPENT";
worksheet.Range["E5:G5"].Merge();
worksheet.Range["E5"].Value = "SUMMARY";
worksheet.Range["E3:F3"].Merge();
worksheet.Range["E9"].Value = "BALANCE";
worksheet.Range["E6"].Value = "Total Monthly Income";
worksheet.Range["E7"].Value = "Total Monthly Expenses";

At this point, the first worksheet contains raw budgeting data and section headers ready for tables and formulas. To learn more about importing and assigning data to worksheet ranges, review the range data import documentation and related demos.

Raw Budget Data Worksheet Example

Step 3: Create Excel Tables

Excel tables make spreadsheet data easier to work with by providing structure, styling, and named references.

In this example, we create two tables: one for income and one for expenses.

// Create the first table to show Income.
ITable incomeTable = worksheet.Tables.Add(worksheet.Range["B3:C7"], true);
incomeTable.Name = "tblIncome";
incomeTable.TableStyle = workbook.TableStyles["TableStyleMedium4"];

// Create the second table to show Expenses.
ITable expensesTable = worksheet.Tables.Add(worksheet.Range["B10:C23"], true);
expensesTable.Name = "tblExpenses";
expensesTable.TableStyle = workbook.TableStyles["TableStyleMedium4"];

The workbook now contains two structured Excel tables with a built-in table style applied to each. For more table creation examples, see the DsExcel .NET Tables demos and documentation.

Programmatically Structed XLSX Data | .NET Developer Solutions

Step 4: Add Formulas and Named Ranges

Named ranges make formulas easier to read and maintain. Here, we define names for total monthly income and total monthly expenses.

worksheet.Names.Add("TotalMonthlyIncome", "=SUM(tblIncome[AMOUNT])");
worksheet.Names.Add("TotalMonthlyExpenses", "=SUM(tblExpenses[AMOUNT])");

Now use those names in worksheet formulas to calculate the summary values.

worksheet.Range["E3"].Formula = "=TotalMonthlyExpenses";
worksheet.Range["G3"].Formula = "=TotalMonthlyExpenses/TotalMonthlyIncome";
worksheet.Range["G6"].Formula = "=TotalMonthlyIncome";
worksheet.Range["G7"].Formula = "=TotalMonthlyExpenses";
worksheet.Range["G9"].Formula = "=TotalMonthlyIncome-TotalMonthlyExpenses";

These formulas generate the expense total, percentage of income spent, total income, total expenses, and remaining balance automatically. To explore formula support and named range usage, review the formula documentation and related demos.

Step 5: Apply Styles and Formatting

Once the spreadsheet logic is in place, improve the worksheet presentation using row and column sizing, workbook styles, and direct range formatting.

Set Row Heights and Column Widths

Begin by adjusting the overall worksheet layout.

worksheet.StandardHeight = 26.25;
worksheet.StandardWidth = 8.43;

worksheet.Range["2:24"].RowHeight = 27;
worksheet.Range["A:A"].ColumnWidth = 2.855;
worksheet.Range["B:B"].ColumnWidth = 33.285;
worksheet.Range["C:C"].ColumnWidth = 25.57;
worksheet.Range["D:D"].ColumnWidth = 1;
worksheet.Range["E:F"].ColumnWidth = 25.57;
worksheet.Range["G:G"].ColumnWidth = 14.285;

Customize Built-In Styles

Next, customize the workbook’s built-in styles for currency values, headings, and percentages.

// Change the currency style
IStyle currencyStyle = workbook.Styles["Currency"];
currencyStyle.IncludeAlignment = true;
currencyStyle.HorizontalAlignment = HorizontalAlignment.Left;
currencyStyle.VerticalAlignment = VerticalAlignment.Bottom;
currencyStyle.NumberFormat = "$#,##0.00";

// Change the heading 1 style
IStyle heading1Style = workbook.Styles["Heading 1"];
heading1Style.IncludeAlignment = true;
heading1Style.HorizontalAlignment = HorizontalAlignment.Center;
heading1Style.VerticalAlignment = VerticalAlignment.Center;
heading1Style.Font.Name = "Century Gothic";
heading1Style.Font.Bold = true;
heading1Style.Font.Size = 11;
heading1Style.Font.Color = Color.White;
heading1Style.IncludeBorder = false;
heading1Style.IncludePatterns = true;
heading1Style.Interior.Color = Color.FromRGB(32, 61, 64);

// Change the percent style
IStyle percentStyle = workbook.Styles["Percent"];
percentStyle.IncludeAlignment = true;
percentStyle.HorizontalAlignment = HorizontalAlignment.Center;
percentStyle.IncludeFont = true;
percentStyle.Font.Color = Color.FromRGB(32, 61, 64);
percentStyle.Font.Name = "Century Gothic";
percentStyle.Font.Bold = true;
percentStyle.Font.Size = 14;

Apply those styles to the appropriate worksheet ranges and hide the gridlines for a cleaner appearance.

worksheet.SheetView.DisplayGridlines = false;

worksheet.Range["C4:C7, C11:C23, G6:G7, G9"].Style = currencyStyle;
worksheet.Range["B2, B9, E2, E5"].Style = heading1Style;
worksheet.Range["G3"].Style = percentStyle;

Apply Direct Range Formatting

You can also set individual formatting properties for specific areas.

worksheet.Range["E6:G6"].Borders[BordersIndex.EdgeBottom].LineStyle = BorderLineStyle.Medium;
worksheet.Range["E6:G6"].Borders[BordersIndex.EdgeBottom].Color = Color.FromRGB(32, 61, 64);

worksheet.Range["E7:G7"].Borders[BordersIndex.EdgeBottom].LineStyle = BorderLineStyle.Medium;
worksheet.Range["E7:G7"].Borders[BordersIndex.EdgeBottom].Color = Color.FromRGB(32, 61, 64);

worksheet.Range["E9:G9"].Interior.Color = Color.FromRGB(32, 61, 64);
worksheet.Range["E9:G9"].HorizontalAlignment = HorizontalAlignment.Left;
worksheet.Range["E9:G9"].VerticalAlignment = VerticalAlignment.Center;
worksheet.Range["E9:G9"].Font.Name = "Century Gothic";
worksheet.Range["E9:G9"].Font.Bold = true;
worksheet.Range["E9:G9"].Font.Size = 11;
worksheet.Range["E9:G9"].Font.Color = Color.White;

worksheet.Range["E3:F3"].Borders.Color = Color.FromRGB(32, 61, 64);

At this stage, the worksheet now contains structured tables, formulas, and polished formatting suitable for reporting. For more examples of workbook styling, number formats, borders, fonts, and range formatting, see the styles documentation and formatting demos.

Programmatically Generate Structured XLSX Files | Developer Solutions | .NET Excel API Library

Step 6: Add Conditional Formatting

Conditional formatting can add visual emphasis and make spreadsheet output easier to interpret.

In this example, we apply a data bar to help represent the expense value relative to monthly income.

IDataBar dataBar = worksheet.Range["E3"].FormatConditions.AddDatabar();
dataBar.MinPoint.Type = ConditionValueTypes.Number;
dataBar.MinPoint.Value = 1;
dataBar.MaxPoint.Type = ConditionValueTypes.Number;
dataBar.MaxPoint.Value = "=TotalMonthlyIncome";

dataBar.BarFillType = DataBarFillType.Gradient;
dataBar.BarColor.Color = Color.Red;
dataBar.ShowValue = false;

This adds a visual indicator directly inside the cell, which can be useful in dashboards and executive reports. To learn more about data bars and other visual rules, review the conditional formatting documentation and demos.

Add visual indicators to C# generated XLSX Files | .NET XLSX API Library

Step 7: Create a Pivot Table

Next, add a second worksheet and build a pivot table to summarize sales data.

First, create the worksheet.

IWorksheet worksheet2 = workbook.Worksheets.AddAfter(worksheet);
worksheet2.Name = "Pivot Table";

Now define the source data for the pivot table.

object[,] sourceData = new object[,]
{
   { "Order ID", "Product",  "Category",   "Amount", "Date",                    "Country" },
   { 1,          "Carrots",  "Vegetables",  4270,    new DateTime(2017, 9, 6),  "United States" },
   { 2,          "Broccoli", "Vegetables",  8239,    new DateTime(2017, 9, 7),  "United Kingdom" },
   { 3,          "Banana",   "Fruit",       617,     new DateTime(2017, 9, 8),  "United States" },
   { 4,          "Banana",   "Fruit",       8384,    new DateTime(2017, 9, 10), "Canada" },
   { 5,          "Beans",    "Vegetables",  2626,    new DateTime(2017, 9, 10), "Germany" },
   { 6,          "Orange",   "Fruit",       3610,    new DateTime(2017, 9, 11), "United States" },
   { 7,          "Broccoli", "Vegetables",  9062,    new DateTime(2017, 9, 11), "Australia" },
   { 8,          "Banana",   "Fruit",       6906,    new DateTime(2017, 9, 16), "New Zealand" },
   { 9,          "Apple",    "Fruit",       2417,    new DateTime(2017, 9, 16), "France" },
   { 10,         "Apple",    "Fruit",       7431,    new DateTime(2017, 9, 16), "Canada" },
   { 11,         "Banana",   "Fruit",       8250,    new DateTime(2017, 9, 16), "Germany" },
   { 12,         "Broccoli", "Vegetables",  7012,    new DateTime(2017, 9, 18), "United States" },
   { 13,         "Carrots",  "Vegetables",  1903,    new DateTime(2017, 9, 20), "Germany" },
   { 14,         "Broccoli", "Vegetables",  2824,    new DateTime(2017, 9, 22), "Canada" },
   { 15,         "Apple",    "Fruit",       6946,    new DateTime(2017, 9, 24), "France" },
};

Write the data to the worksheet and create the pivot cache and pivot table.

worksheet2.Range["A1:F16"].Value = sourceData;
worksheet2.Range["A:F"].ColumnWidth = 15;
worksheet2.Range["H:I"].ColumnWidth = 15;

var pivotcache = workbook.PivotCaches.Create(worksheet2.Range["A1:F16"]);
var pivottable = worksheet2.PivotTables.Add(pivotcache, worksheet2.Range["A21"], "pivottable1");

Finally, configure the pivot table fields.

var field_Category = pivottable.PivotFields["Category"];
field_Category.Orientation = PivotFieldOrientation.RowField;

var field_Product = pivottable.PivotFields["Product"];
field_Product.Orientation = PivotFieldOrientation.ColumnField;

var field_Amount = pivottable.PivotFields["Amount"];
field_Amount.Orientation = PivotFieldOrientation.DataField;

var field_Country = pivottable.PivotFields["Country"];
field_Country.Orientation = PivotFieldOrientation.PageField;

At this point, the workbook contains a fully generated pivot table that summarizes the sales data programmatically. For more pivot table examples, see the Pivot Table demos and documentation.

Programmatically Generate Pivot Tables using C# | .NET Excel API Library

Step 8: Add a Chart

Next, create a third worksheet and add a chart to visualize quarterly data.

Start by adding the worksheet.

IWorksheet worksheet3 = workbook.Worksheets.AddAfter(worksheet2);
worksheet3.Name = "Chart";

In DsExcel .NET, charts are created as shapes. First, add a chart shape and define its type, position, and size.

IShape shape = worksheet3.Shapes.AddChart(ChartType.ColumnClustered, 300, 10, 300, 300);

Now set the chart title and populate the chart data range.

shape.Chart.ChartTitle.Text = "Sales Increases Over Previous Quarter";

worksheet3.Range["A1:D6"].Value = new object[,]
{
   {null, "Q1", "Q2", "Q3"},
   {"Belgium", 10, 25, 25},
   {"France", -51, -36, 27},
   {"Greece", 52, -85, -30},
   {"Italy", 22, 65, 65},
   {"UK", 23, 69, 69}
};

shape.Chart.SeriesCollection.Add(worksheet3.Range["A1:D6"], RowCol.Columns, true, true);

To improve the presentation, format the data range and the chart’s value axis.

worksheet3.Range["B1:D1"].HorizontalAlignment = HorizontalAlignment.Right;
worksheet3.Range["B1:D1"].Font.Bold = true;
worksheet3.Range["B2:D6"].NumberFormat = "€#,##0";

IAxis value_axis = shape.Chart.Axes.Item(AxisType.Value);
value_axis.TickLabels.NumberFormat = "€#,##0";

The workbook now contains a third worksheet with a formatted clustered column chart. To explore additional chart types and configuration options, review the Chart demos and documentation.

Programmatically generate XLSX files with charts using C# and a .NET Excel API

Step 9: Save the Excel File

Finally, save the workbook as an XLSX file.

workbook.Save("3-sheet-sample.xlsx");

When you open the saved workbook, you will see:

  • a formatted worksheet with income and expense tables
  • summary formulas and conditional formatting
  • a pivot table worksheet for summarizing data
  • a chart worksheet for visual reporting

This demonstrates how to build a complete, multi-sheet Excel file programmatically using C# and .NET. For more information on saving and exporting workbooks, see the save/export documentation.


Download a Free Trial of this .NET Excel API Library Today!

Summary

In this tutorial, you learned how to generate Excel spreadsheets programmatically using Document Solutions for Excel .NET and C#.

We covered how to:

  • create a workbook and worksheets
  • populate ranges with data
  • build Excel tables
  • add named ranges and formulas
  • apply formatting and styles
  • use conditional formatting
  • generate a pivot table
  • create a chart
  • save the workbook to XLSX

Using DsExcel .NET, developers can create rich spreadsheet documents entirely in code without depending on Microsoft Excel.

This enables powerful automation scenarios such as:

  • server-side report generation
  • business data exports
  • dashboard creation
  • financial workbook automation
  • multi-sheet spreadsheet workflows

To explore more capabilities, review the Document Solutions for Excel .NET documentation and demos.

Tags:

comments powered by Disqus