Comment créer un fichier Excel en C#

How to Create Excel Files in C# Without Interop

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

Learn how to generate Excel files in C# using IronXL - a powerful .NET Excel library that creates, reads, and edits spreadsheets without Microsoft Office dependencies. This comprehensive tutorial walks you through building Excel workbooks programmatically with step-by-step code examples.

Quickstart: Simple One-Line Excel Workbook Creation

Use IronXL to spin up a new Excel file in no time—just pick a format, add a sheet, set any cell value, and save. It’s the quickest way to generate XLSX files with intuitive API calls and zero interop headaches.

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.

    WorkBook book = IronXL.WorkBook.Create(IronXL.ExcelFileFormat.XLSX); book.CreateWorkSheet("Sheet1")["A1"].Value = "Hello World"; book.SaveAs("MyFile.xlsx");
  3. Deploy to test on your live environment

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

Overview

What is IronXL and Why Use It for Excel File Creation?

IronXL is an intuitive C# & VB Excel API that enables you to read, edit, and create Excel spreadsheet files in .NET with exceptional performance. Unlike traditional approaches, there's no need to install Microsoft Office or use Excel Interop, making deployment simpler and more reliable.

IronXL fully supports .NET 9, .NET 8, .NET Core, .NET Framework, Xamarin, Mobile, Linux, macOS, and Azure environments.

IronXL Features

  • Human support directly from our .NET development team
  • Rapid installation with Microsoft Visual Studio
  • FREE for development. Licenses from $799

How Can I Quickly Create and Save an Excel File?

Install IronXL via NuGet or download the DLL directly.

using IronXL;

// Create a new Excel workbook with XLSX format
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);

// Add a worksheet to the workbook
var workSheet = workBook.CreateWorkSheet("example_sheet");

// Set individual cell values using intuitive syntax
workSheet["A1"].Value = "Example";

// Set multiple cells at once using range syntax
workSheet["A2:A4"].Value = 5;

// Apply cell styling - set background color using hex code
workSheet["A5"].Style.SetBackgroundColor("#f0f0f0");

// Make text bold for better visibility
workSheet["A5:A6"].Style.Font.Bold = true;

// Add Excel formula to calculate sum
workSheet["A6"].Formula = "=SUM(A2:A4)";

// Calculate all formulas to show results
workSheet.EvaluateAll();

// Verify formula calculation worked correctly
if (workSheet["A6"].IntValue == 15) // Sum of three cells with value 5
{
    Console.WriteLine("Formula calculation successful!");
}

// Save the Excel file to disk
workBook.SaveAs("example_workbook.xlsx");
using IronXL;

// Create a new Excel workbook with XLSX format
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);

// Add a worksheet to the workbook
var workSheet = workBook.CreateWorkSheet("example_sheet");

// Set individual cell values using intuitive syntax
workSheet["A1"].Value = "Example";

// Set multiple cells at once using range syntax
workSheet["A2:A4"].Value = 5;

// Apply cell styling - set background color using hex code
workSheet["A5"].Style.SetBackgroundColor("#f0f0f0");

// Make text bold for better visibility
workSheet["A5:A6"].Style.Font.Bold = true;

// Add Excel formula to calculate sum
workSheet["A6"].Formula = "=SUM(A2:A4)";

// Calculate all formulas to show results
workSheet.EvaluateAll();

// Verify formula calculation worked correctly
if (workSheet["A6"].IntValue == 15) // Sum of three cells with value 5
{
    Console.WriteLine("Formula calculation successful!");
}

// Save the Excel file to disk
workBook.SaveAs("example_workbook.xlsx");
Imports IronXL

' Create a new Excel workbook with XLSX format
Private workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

' Add a worksheet to the workbook
Private workSheet = workBook.CreateWorkSheet("example_sheet")

' Set individual cell values using intuitive syntax
Private workSheet("A1").Value = "Example"

' Set multiple cells at once using range syntax
Private workSheet("A2:A4").Value = 5

' Apply cell styling - set background color using hex code
workSheet("A5").Style.SetBackgroundColor("#f0f0f0")

' Make text bold for better visibility
workSheet("A5:A6").Style.Font.Bold = True

' Add Excel formula to calculate sum
workSheet("A6").Formula = "=SUM(A2:A4)"

' Calculate all formulas to show results
workSheet.EvaluateAll()

' Verify formula calculation worked correctly
If workSheet("A6").IntValue = 15 Then ' Sum of three cells with value 5
	Console.WriteLine("Formula calculation successful!")
End If

' Save the Excel file to disk
workBook.SaveAs("example_workbook.xlsx")
$vbLabelText   $csharpLabel

This code demonstrates key IronXL features: creating workbooks, adding worksheets, setting cell values and styles, using formulas, and saving files. The WorkBook class serves as your entry point for all Excel operations, while the WorkSheet class provides methods to manipulate individual sheets.


Step 1

1. How Do I Install the IronXL C# Library?

Install the IronXL library using NuGet (Install-Package IronXL) or by downloading the DLL directly.

Commencez à utiliser IronXL dans votre projet aujourd'hui avec un essai gratuit.

Première étape :
green arrow pointer


How Can I Install IronXL Using NuGet?

There are three ways to install the IronXL NuGet package:

  1. Visual Studio Package Manager
  2. Developer Command Prompt
  3. Direct download from NuGet.org

Visual Studio Installation

Visual Studio provides the NuGet Package Manager for easy package installation. Access it via the Project Menu or by right-clicking your project in Solution Explorer.

Visual Studio Project menu showing Manage NuGet Packages option

Figure 3Access NuGet Package Manager through Project menu

Solution Explorer context menu displaying Manage NuGet Packages option

Figure 4Right-click context menu in Solution Explorer


After clicking Manage NuGet Packages, browse for the IronXL.Excel package and install it.


NuGet Package Manager showing IronXL.Excel package ready for installation

Figure 5Installing IronXL.Excel through NuGet Package Manager

Developer Command Prompt Installation

Use the Package Manager Console with this command:

Install-Package IronXL.Excel

Direct Download Installation

  1. Navigate to: https://www.nuget.org/packages/IronXL.Excel/
  2. Click Download Package
  3. Double-click the downloaded package
  4. Reload your Visual Studio project

How Do I Install IronXL by Downloading the DLL?

Download IronXL directly from: https://ironsoftware.com/csharp/excel/

IronXL website download page showing installation instructions and download button

Figure 6Download IronXL library from official website

Reference the library in your project:

  1. Right-click the Solution in Solution Explorer
  2. Select References
  3. Browse for the IronXL.dll library
  4. Click OK

Let's Go!

Now you're ready to explore IronXL's powerful Excel manipulation features!


How to Tutorials

2. How Do I Create an ASP.NET Project for Excel Generation?

Follow these steps to create an ASP.NET website:

  1. Open Visual Studio
  2. Click File > New Project
  3. Select Web under Visual C# in the Project type list
  4. Select ASP.NET Web Application


    Visual Studio New Project dialog with ASP.NET Web Application selected

    Figure 1Create new ASP.NET project

  5. Click OK
  6. Select Web Forms template

    ASP.NET project template selection showing Web Forms option

    Figure 2Select Web Forms template

  7. Click OK

With your project ready, install IronXL to start creating Excel files programmatically.


3. How Do I Create an Excel Workbook in C#?

Creating a new Excel workbook with IronXL requires just one line of code:

using IronXL;

// Create workbook with XLSX format (recommended for modern Excel)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);

// Alternative: Create legacy XLS format for older Excel versions
WorkBook legacyWorkbook = WorkBook.Create(ExcelFileFormat.XLS);
using IronXL;

// Create workbook with XLSX format (recommended for modern Excel)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);

// Alternative: Create legacy XLS format for older Excel versions
WorkBook legacyWorkbook = WorkBook.Create(ExcelFileFormat.XLS);
Imports IronXL

' Create workbook with XLSX format (recommended for modern Excel)
Private workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

' Alternative: Create legacy XLS format for older Excel versions
Private legacyWorkbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
$vbLabelText   $csharpLabel

The WorkBook.Create method supports both XLS (Excel 97-2003) and XLSX (Excel 2007+) formats. XLSX is recommended for better performance and smaller file sizes.

3.1. How Do I Add a Worksheet to My Workbook?

Adding worksheets is straightforward:

// Create a worksheet with custom name for budget tracking
WorkSheet budgetSheet = workbook.CreateWorkSheet("2020 Budget");

// Add multiple worksheets for different purposes
WorkSheet salesSheet = workbook.CreateWorkSheet("Sales Data");
WorkSheet inventorySheet = workbook.CreateWorkSheet("Inventory");

// Access existing worksheet by name
WorkSheet existingSheet = workbook.GetWorkSheet("2020 Budget");
// Create a worksheet with custom name for budget tracking
WorkSheet budgetSheet = workbook.CreateWorkSheet("2020 Budget");

// Add multiple worksheets for different purposes
WorkSheet salesSheet = workbook.CreateWorkSheet("Sales Data");
WorkSheet inventorySheet = workbook.CreateWorkSheet("Inventory");

// Access existing worksheet by name
WorkSheet existingSheet = workbook.GetWorkSheet("2020 Budget");
' Create a worksheet with custom name for budget tracking
Dim budgetSheet As WorkSheet = workbook.CreateWorkSheet("2020 Budget")

' Add multiple worksheets for different purposes
Dim salesSheet As WorkSheet = workbook.CreateWorkSheet("Sales Data")
Dim inventorySheet As WorkSheet = workbook.CreateWorkSheet("Inventory")

' Access existing worksheet by name
Dim existingSheet As WorkSheet = workbook.GetWorkSheet("2020 Budget")
$vbLabelText   $csharpLabel

A workbook contains one or more worksheets. Each worksheet consists of rows and columns, with cells at their intersections. Use the CreateWorkSheet method to add new sheets to your workbook.


4. How Do I Set Cell Values in Excel?

4.1. How Can I Set Cell Values Manually?

Setting individual cell values uses intuitive Excel-like syntax:

// Set month names in first row for annual budget spreadsheet
workSheet["A1"].Value = "January";
workSheet["B1"].Value = "February";
workSheet["C1"].Value = "March";
workSheet["D1"].Value = "April";
workSheet["E1"].Value = "May";
workSheet["F1"].Value = "June";
workSheet["G1"].Value = "July";
workSheet["H1"].Value = "August";
workSheet["I1"].Value = "September";
workSheet["J1"].Value = "October";
workSheet["K1"].Value = "November";
workSheet["L1"].Value = "December";

// Set different data types - IronXL handles conversion automatically
workSheet["A2"].Value = 1500.50m;  // Decimal for currency
workSheet["A3"].Value = DateTime.Now;  // Date values
workSheet["A4"].Value = true;  // Boolean values
// Set month names in first row for annual budget spreadsheet
workSheet["A1"].Value = "January";
workSheet["B1"].Value = "February";
workSheet["C1"].Value = "March";
workSheet["D1"].Value = "April";
workSheet["E1"].Value = "May";
workSheet["F1"].Value = "June";
workSheet["G1"].Value = "July";
workSheet["H1"].Value = "August";
workSheet["I1"].Value = "September";
workSheet["J1"].Value = "October";
workSheet["K1"].Value = "November";
workSheet["L1"].Value = "December";

// Set different data types - IronXL handles conversion automatically
workSheet["A2"].Value = 1500.50m;  // Decimal for currency
workSheet["A3"].Value = DateTime.Now;  // Date values
workSheet["A4"].Value = true;  // Boolean values
' Set month names in first row for annual budget spreadsheet
workSheet("A1").Value = "January"
workSheet("B1").Value = "February"
workSheet("C1").Value = "March"
workSheet("D1").Value = "April"
workSheet("E1").Value = "May"
workSheet("F1").Value = "June"
workSheet("G1").Value = "July"
workSheet("H1").Value = "August"
workSheet("I1").Value = "September"
workSheet("J1").Value = "October"
workSheet("K1").Value = "November"
workSheet("L1").Value = "December"

' Set different data types - IronXL handles conversion automatically
workSheet("A2").Value = 1500.50D ' Decimal for currency
workSheet("A3").Value = DateTime.Now ' Date values
workSheet("A4").Value = True ' Boolean values
$vbLabelText   $csharpLabel

The Cell.Value property accepts various data types including strings, numbers, dates, and booleans. IronXL automatically formats cells based on the data type.

4.2. How Do I Set Cell Values Dynamically?

Dynamic value setting is perfect for data-driven applications:

// Initialize random number generator for sample data
Random r = new Random();

// Populate cells with random budget data for each month
for (int i = 2; i <= 11; i++)
{
    // Set different budget categories with increasing ranges
    workSheet[$"A{i}"].Value = r.Next(1, 1000);     // Office Supplies
    workSheet[$"B{i}"].Value = r.Next(1000, 2000);  // Utilities
    workSheet[$"C{i}"].Value = r.Next(2000, 3000);  // Rent
    workSheet[$"D{i}"].Value = r.Next(3000, 4000);  // Salaries
    workSheet[$"E{i}"].Value = r.Next(4000, 5000);  // Marketing
    workSheet[$"F{i}"].Value = r.Next(5000, 6000);  // IT Services
    workSheet[$"G{i}"].Value = r.Next(6000, 7000);  // Travel
    workSheet[$"H{i}"].Value = r.Next(7000, 8000);  // Training
    workSheet[$"I{i}"].Value = r.Next(8000, 9000);  // Insurance
    workSheet[$"J{i}"].Value = r.Next(9000, 10000); // Equipment
    workSheet[$"K{i}"].Value = r.Next(10000, 11000); // Research
    workSheet[$"L{i}"].Value = r.Next(11000, 12000); // Misc
}

// Alternative: Set range of cells with same value
workSheet["A13:L13"].Value = 0; // Initialize totals row
// Initialize random number generator for sample data
Random r = new Random();

// Populate cells with random budget data for each month
for (int i = 2; i <= 11; i++)
{
    // Set different budget categories with increasing ranges
    workSheet[$"A{i}"].Value = r.Next(1, 1000);     // Office Supplies
    workSheet[$"B{i}"].Value = r.Next(1000, 2000);  // Utilities
    workSheet[$"C{i}"].Value = r.Next(2000, 3000);  // Rent
    workSheet[$"D{i}"].Value = r.Next(3000, 4000);  // Salaries
    workSheet[$"E{i}"].Value = r.Next(4000, 5000);  // Marketing
    workSheet[$"F{i}"].Value = r.Next(5000, 6000);  // IT Services
    workSheet[$"G{i}"].Value = r.Next(6000, 7000);  // Travel
    workSheet[$"H{i}"].Value = r.Next(7000, 8000);  // Training
    workSheet[$"I{i}"].Value = r.Next(8000, 9000);  // Insurance
    workSheet[$"J{i}"].Value = r.Next(9000, 10000); // Equipment
    workSheet[$"K{i}"].Value = r.Next(10000, 11000); // Research
    workSheet[$"L{i}"].Value = r.Next(11000, 12000); // Misc
}

// Alternative: Set range of cells with same value
workSheet["A13:L13"].Value = 0; // Initialize totals row
' Initialize random number generator for sample data
Dim r As New Random()

' Populate cells with random budget data for each month
For i As Integer = 2 To 11
	' Set different budget categories with increasing ranges
	workSheet($"A{i}").Value = r.Next(1, 1000) ' Office Supplies
	workSheet($"B{i}").Value = r.Next(1000, 2000) ' Utilities
	workSheet($"C{i}").Value = r.Next(2000, 3000) ' Rent
	workSheet($"D{i}").Value = r.Next(3000, 4000) ' Salaries
	workSheet($"E{i}").Value = r.Next(4000, 5000) ' Marketing
	workSheet($"F{i}").Value = r.Next(5000, 6000) ' IT Services
	workSheet($"G{i}").Value = r.Next(6000, 7000) ' Travel
	workSheet($"H{i}").Value = r.Next(7000, 8000) ' Training
	workSheet($"I{i}").Value = r.Next(8000, 9000) ' Insurance
	workSheet($"J{i}").Value = r.Next(9000, 10000) ' Equipment
	workSheet($"K{i}").Value = r.Next(10000, 11000) ' Research
	workSheet($"L{i}").Value = r.Next(11000, 12000) ' Misc
Next i

' Alternative: Set range of cells with same value
workSheet("A13:L13").Value = 0 ' Initialize totals row
$vbLabelText   $csharpLabel

String interpolation ($"A{i}") makes it easy to reference cells dynamically. The Range indexer supports both individual cells and ranges.

4.3. How Do I Populate Excel from a Database?

Loading data from databases into Excel is a common requirement:

using System.Data;
using System.Data.SqlClient;
using IronXL;

// Database connection setup for retrieving sales data
string connectionString = @"Data Source=ServerName;Initial Catalog=SalesDB;Integrated Security=true";
string query = "SELECT ProductName, Quantity, UnitPrice, TotalSales FROM MonthlySales";

// Create DataSet to hold query results
DataSet salesData = new DataSet();

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
    // Fill DataSet with sales information
    adapter.Fill(salesData);
}

// Write headers for database columns
workSheet["A1"].Value = "Product Name";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Unit Price";
workSheet["D1"].Value = "Total Sales";

// Apply header formatting
workSheet["A1:D1"].Style.Font.Bold = true;
workSheet["A1:D1"].Style.SetBackgroundColor("#4472C4");
workSheet["A1:D1"].Style.Font.FontColor = "#FFFFFF";

// Populate Excel with database records
DataTable salesTable = salesData.Tables[0];
for (int row = 0; row < salesTable.Rows.Count; row++)
{
    int excelRow = row + 2; // Start from row 2 (after headers)

    workSheet[$"A{excelRow}"].Value = salesTable.Rows[row]["ProductName"].ToString();
    workSheet[$"B{excelRow}"].Value = Convert.ToInt32(salesTable.Rows[row]["Quantity"]);
    workSheet[$"C{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["UnitPrice"]);
    workSheet[$"D{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["TotalSales"]);

    // Format currency columns
    workSheet[$"C{excelRow}"].FormatString = "$#,##0.00";
    workSheet[$"D{excelRow}"].FormatString = "$#,##0.00";
}

// Add summary row with formulas
int summaryRow = salesTable.Rows.Count + 2;
workSheet[$"A{summaryRow}"].Value = "TOTAL";
workSheet[$"B{summaryRow}"].Formula = $"=SUM(B2:B{summaryRow-1})";
workSheet[$"D{summaryRow}"].Formula = $"=SUM(D2:D{summaryRow-1})";
using System.Data;
using System.Data.SqlClient;
using IronXL;

// Database connection setup for retrieving sales data
string connectionString = @"Data Source=ServerName;Initial Catalog=SalesDB;Integrated Security=true";
string query = "SELECT ProductName, Quantity, UnitPrice, TotalSales FROM MonthlySales";

// Create DataSet to hold query results
DataSet salesData = new DataSet();

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
    // Fill DataSet with sales information
    adapter.Fill(salesData);
}

// Write headers for database columns
workSheet["A1"].Value = "Product Name";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Unit Price";
workSheet["D1"].Value = "Total Sales";

// Apply header formatting
workSheet["A1:D1"].Style.Font.Bold = true;
workSheet["A1:D1"].Style.SetBackgroundColor("#4472C4");
workSheet["A1:D1"].Style.Font.FontColor = "#FFFFFF";

// Populate Excel with database records
DataTable salesTable = salesData.Tables[0];
for (int row = 0; row < salesTable.Rows.Count; row++)
{
    int excelRow = row + 2; // Start from row 2 (after headers)

    workSheet[$"A{excelRow}"].Value = salesTable.Rows[row]["ProductName"].ToString();
    workSheet[$"B{excelRow}"].Value = Convert.ToInt32(salesTable.Rows[row]["Quantity"]);
    workSheet[$"C{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["UnitPrice"]);
    workSheet[$"D{excelRow}"].Value = Convert.ToDecimal(salesTable.Rows[row]["TotalSales"]);

    // Format currency columns
    workSheet[$"C{excelRow}"].FormatString = "$#,##0.00";
    workSheet[$"D{excelRow}"].FormatString = "$#,##0.00";
}

// Add summary row with formulas
int summaryRow = salesTable.Rows.Count + 2;
workSheet[$"A{summaryRow}"].Value = "TOTAL";
workSheet[$"B{summaryRow}"].Formula = $"=SUM(B2:B{summaryRow-1})";
workSheet[$"D{summaryRow}"].Formula = $"=SUM(D2:D{summaryRow-1})";
Imports System.Data
Imports System.Data.SqlClient
Imports IronXL

' Database connection setup for retrieving sales data
Private connectionString As String = "Data Source=ServerName;Initial Catalog=SalesDB;Integrated Security=true"
Private query As String = "SELECT ProductName, Quantity, UnitPrice, TotalSales FROM MonthlySales"

' Create DataSet to hold query results
Private salesData As New DataSet()

Using connection As New SqlConnection(connectionString)
Using adapter As New SqlDataAdapter(query, connection)
	' Fill DataSet with sales information
	adapter.Fill(salesData)
End Using
End Using

' Write headers for database columns
workSheet("A1").Value = "Product Name"
workSheet("B1").Value = "Quantity"
workSheet("C1").Value = "Unit Price"
workSheet("D1").Value = "Total Sales"

' Apply header formatting
workSheet("A1:D1").Style.Font.Bold = True
workSheet("A1:D1").Style.SetBackgroundColor("#4472C4")
workSheet("A1:D1").Style.Font.FontColor = "#FFFFFF"

' Populate Excel with database records
Dim salesTable As DataTable = salesData.Tables(0)
For row As Integer = 0 To salesTable.Rows.Count - 1
	Dim excelRow As Integer = row + 2 ' Start from row 2 (after headers)

	workSheet($"A{excelRow}").Value = salesTable.Rows(row)("ProductName").ToString()
	workSheet($"B{excelRow}").Value = Convert.ToInt32(salesTable.Rows(row)("Quantity"))
	workSheet($"C{excelRow}").Value = Convert.ToDecimal(salesTable.Rows(row)("UnitPrice"))
	workSheet($"D{excelRow}").Value = Convert.ToDecimal(salesTable.Rows(row)("TotalSales"))

	' Format currency columns
	workSheet($"C{excelRow}").FormatString = "$#,##0.00"
	workSheet($"D{excelRow}").FormatString = "$#,##0.00"
Next row

' Add summary row with formulas
Dim summaryRow As Integer = salesTable.Rows.Count + 2
workSheet($"A{summaryRow}").Value = "TOTAL"
workSheet($"B{summaryRow}").Formula = $"=SUM(B2:B{summaryRow-1})"
workSheet($"D{summaryRow}").Formula = $"=SUM(D2:D{summaryRow-1})"
$vbLabelText   $csharpLabel

This example demonstrates reading Excel data from databases, applying formatting, and using formulas for calculations. The FormatString property enables custom number formatting just like in Excel.


5. How Do I Apply Formatting to Excel Cells?

5.1. How Can I Set Background Colors in Excel?

Cell styling enhances readability and visual appeal:

// Set header row background to light gray using hex color
workSheet["A1:L1"].Style.SetBackgroundColor("#d3d3d3");

// Apply different colors for data categorization
workSheet["A2:A11"].Style.SetBackgroundColor("#E7F3FF"); // Light blue for January
workSheet["B2:B11"].Style.SetBackgroundColor("#FFF2CC"); // Light yellow for February

// Highlight important cells with bold colors
workSheet["L12"].Style.SetBackgroundColor("#FF0000"); // Red for totals
workSheet["L12"].Style.Font.FontColor = "#FFFFFF"; // White text

// Create alternating row colors for better readability
for (int row = 2; row <= 11; row++)
{
    if (row % 2 == 0)
    {
        workSheet[$"A{row}:L{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
// Set header row background to light gray using hex color
workSheet["A1:L1"].Style.SetBackgroundColor("#d3d3d3");

// Apply different colors for data categorization
workSheet["A2:A11"].Style.SetBackgroundColor("#E7F3FF"); // Light blue for January
workSheet["B2:B11"].Style.SetBackgroundColor("#FFF2CC"); // Light yellow for February

// Highlight important cells with bold colors
workSheet["L12"].Style.SetBackgroundColor("#FF0000"); // Red for totals
workSheet["L12"].Style.Font.FontColor = "#FFFFFF"; // White text

// Create alternating row colors for better readability
for (int row = 2; row <= 11; row++)
{
    if (row % 2 == 0)
    {
        workSheet[$"A{row}:L{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
' Set header row background to light gray using hex color
workSheet("A1:L1").Style.SetBackgroundColor("#d3d3d3")

' Apply different colors for data categorization
workSheet("A2:A11").Style.SetBackgroundColor("#E7F3FF") ' Light blue for January
workSheet("B2:B11").Style.SetBackgroundColor("#FFF2CC") ' Light yellow for February

' Highlight important cells with bold colors
workSheet("L12").Style.SetBackgroundColor("#FF0000") ' Red for totals
workSheet("L12").Style.Font.FontColor = "#FFFFFF" ' White text

' Create alternating row colors for better readability
For row As Integer = 2 To 11
	If row Mod 2 = 0 Then
		workSheet($"A{row}:L{row}").Style.SetBackgroundColor("#F2F2F2")
	End If
Next row
$vbLabelText   $csharpLabel

The Style.SetBackgroundColor method accepts hex color codes. Combine background colors with font colors for professional-looking spreadsheets.

5.2. How Do I Create Borders in Excel?

Borders help define data regions and improve structure:

using IronXL;
using IronXL.Styles;

// Create header border - thick bottom line to separate from data
workSheet["A1:L1"].Style.TopBorder.SetColor("#000000");
workSheet["A1:L1"].Style.TopBorder.Type = BorderType.Thick;
workSheet["A1:L1"].Style.BottomBorder.SetColor("#000000");
workSheet["A1:L1"].Style.BottomBorder.Type = BorderType.Thick;

// Add right border to last column
workSheet["L2:L11"].Style.RightBorder.SetColor("#000000");
workSheet["L2:L11"].Style.RightBorder.Type = BorderType.Medium;

// Create bottom border for data area
workSheet["A11:L11"].Style.BottomBorder.SetColor("#000000");
workSheet["A11:L11"].Style.BottomBorder.Type = BorderType.Medium;

// Apply complete border around summary section
var summaryRange = workSheet["A12:L12"];
summaryRange.Style.TopBorder.Type = BorderType.Double;
summaryRange.Style.BottomBorder.Type = BorderType.Double;
summaryRange.Style.LeftBorder.Type = BorderType.Thin;
summaryRange.Style.RightBorder.Type = BorderType.Thin;
summaryRange.Style.SetBorderColor("#0070C0"); // Blue borders
using IronXL;
using IronXL.Styles;

// Create header border - thick bottom line to separate from data
workSheet["A1:L1"].Style.TopBorder.SetColor("#000000");
workSheet["A1:L1"].Style.TopBorder.Type = BorderType.Thick;
workSheet["A1:L1"].Style.BottomBorder.SetColor("#000000");
workSheet["A1:L1"].Style.BottomBorder.Type = BorderType.Thick;

// Add right border to last column
workSheet["L2:L11"].Style.RightBorder.SetColor("#000000");
workSheet["L2:L11"].Style.RightBorder.Type = BorderType.Medium;

// Create bottom border for data area
workSheet["A11:L11"].Style.BottomBorder.SetColor("#000000");
workSheet["A11:L11"].Style.BottomBorder.Type = BorderType.Medium;

// Apply complete border around summary section
var summaryRange = workSheet["A12:L12"];
summaryRange.Style.TopBorder.Type = BorderType.Double;
summaryRange.Style.BottomBorder.Type = BorderType.Double;
summaryRange.Style.LeftBorder.Type = BorderType.Thin;
summaryRange.Style.RightBorder.Type = BorderType.Thin;
summaryRange.Style.SetBorderColor("#0070C0"); // Blue borders
Imports IronXL
Imports IronXL.Styles

' Create header border - thick bottom line to separate from data
workSheet("A1:L1").Style.TopBorder.SetColor("#000000")
workSheet("A1:L1").Style.TopBorder.Type = BorderType.Thick
workSheet("A1:L1").Style.BottomBorder.SetColor("#000000")
workSheet("A1:L1").Style.BottomBorder.Type = BorderType.Thick

' Add right border to last column
workSheet("L2:L11").Style.RightBorder.SetColor("#000000")
workSheet("L2:L11").Style.RightBorder.Type = BorderType.Medium

' Create bottom border for data area
workSheet("A11:L11").Style.BottomBorder.SetColor("#000000")
workSheet("A11:L11").Style.BottomBorder.Type = BorderType.Medium

' Apply complete border around summary section
Dim summaryRange = workSheet("A12:L12")
summaryRange.Style.TopBorder.Type = BorderType.Double
summaryRange.Style.BottomBorder.Type = BorderType.Double
summaryRange.Style.LeftBorder.Type = BorderType.Thin
summaryRange.Style.RightBorder.Type = BorderType.Thin
summaryRange.Style.SetBorderColor("#0070C0") ' Blue borders
$vbLabelText   $csharpLabel

IronXL supports various border types including Thin, Medium, Thick, Double, Dotted, and Dashed. Each border side can be styled independently.


6. How Do I Use Excel Formulas in C#?

IronXL provides powerful formula support with automatic calculation:

// Use built-in aggregation functions for ranges
decimal sum = workSheet["A2:A11"].Sum();
decimal avg = workSheet["B2:B11"].Avg();
decimal max = workSheet["C2:C11"].Max();
decimal min = workSheet["D2:D11"].Min();

// Assign calculated values to cells
workSheet["A12"].Value = sum;
workSheet["B12"].Value = avg;
workSheet["C12"].Value = max;
workSheet["D12"].Value = min;

// Or use Excel formulas directly
workSheet["A12"].Formula = "=SUM(A2:A11)";
workSheet["B12"].Formula = "=AVERAGE(B2:B11)";
workSheet["C12"].Formula = "=MAX(C2:C11)";
workSheet["D12"].Formula = "=MIN(D2:D11)";

// Complex formulas with multiple functions
workSheet["E12"].Formula = "=IF(SUM(E2:E11)>50000,\"Over Budget\",\"On Track\")";
workSheet["F12"].Formula = "=SUMIF(F2:F11,\">5000\")";

// Percentage calculations
workSheet["G12"].Formula = "=G11/SUM(G2:G11)*100";
workSheet["G12"].FormatString = "0.00%";

// Ensure all formulas calculate
workSheet.EvaluateAll();
// Use built-in aggregation functions for ranges
decimal sum = workSheet["A2:A11"].Sum();
decimal avg = workSheet["B2:B11"].Avg();
decimal max = workSheet["C2:C11"].Max();
decimal min = workSheet["D2:D11"].Min();

// Assign calculated values to cells
workSheet["A12"].Value = sum;
workSheet["B12"].Value = avg;
workSheet["C12"].Value = max;
workSheet["D12"].Value = min;

// Or use Excel formulas directly
workSheet["A12"].Formula = "=SUM(A2:A11)";
workSheet["B12"].Formula = "=AVERAGE(B2:B11)";
workSheet["C12"].Formula = "=MAX(C2:C11)";
workSheet["D12"].Formula = "=MIN(D2:D11)";

// Complex formulas with multiple functions
workSheet["E12"].Formula = "=IF(SUM(E2:E11)>50000,\"Over Budget\",\"On Track\")";
workSheet["F12"].Formula = "=SUMIF(F2:F11,\">5000\")";

// Percentage calculations
workSheet["G12"].Formula = "=G11/SUM(G2:G11)*100";
workSheet["G12"].FormatString = "0.00%";

// Ensure all formulas calculate
workSheet.EvaluateAll();
' Use built-in aggregation functions for ranges
Dim sum As Decimal = workSheet("A2:A11").Sum()
Dim avg As Decimal = workSheet("B2:B11").Avg()
Dim max As Decimal = workSheet("C2:C11").Max()
Dim min As Decimal = workSheet("D2:D11").Min()

' Assign calculated values to cells
workSheet("A12").Value = sum
workSheet("B12").Value = avg
workSheet("C12").Value = max
workSheet("D12").Value = min

' Or use Excel formulas directly
workSheet("A12").Formula = "=SUM(A2:A11)"
workSheet("B12").Formula = "=AVERAGE(B2:B11)"
workSheet("C12").Formula = "=MAX(C2:C11)"
workSheet("D12").Formula = "=MIN(D2:D11)"

' Complex formulas with multiple functions
workSheet("E12").Formula = "=IF(SUM(E2:E11)>50000,""Over Budget"",""On Track"")"
workSheet("F12").Formula = "=SUMIF(F2:F11,"">5000"")"

' Percentage calculations
workSheet("G12").Formula = "=G11/SUM(G2:G11)*100"
workSheet("G12").FormatString = "0.00%"

' Ensure all formulas calculate
workSheet.EvaluateAll()
$vbLabelText   $csharpLabel

The Range class provides methods like Sum(), Avg(), Max(), and Min() for quick calculations. For more complex scenarios, use the Formula property to set Excel formulas directly.


7. How Do I Set Worksheet and Print Properties?

Use IronXL to protect individual worksheets, freeze rows and columns, and set printing format options.

7.1. How Can I Configure Worksheet Properties?

Protect worksheets and control viewing options:

// Protect worksheet with password to prevent unauthorized changes
workSheet.ProtectSheet("SecurePassword123");

// Freeze panes to keep headers visible while scrolling
workSheet.CreateFreezePane(0, 1); // Freeze first row
// workSheet.CreateFreezePane(1, 1); // Freeze first row and column

// Set worksheet visibility options
workSheet.ViewState = WorkSheetViewState.Visible; // or Hidden, VeryHidden

// Configure gridlines and headers
workSheet.ShowGridLines = true;
workSheet.ShowRowColHeaders = true;

// Set zoom level for better viewing
workSheet.Zoom = 85; // 85% zoom
// Protect worksheet with password to prevent unauthorized changes
workSheet.ProtectSheet("SecurePassword123");

// Freeze panes to keep headers visible while scrolling
workSheet.CreateFreezePane(0, 1); // Freeze first row
// workSheet.CreateFreezePane(1, 1); // Freeze first row and column

// Set worksheet visibility options
workSheet.ViewState = WorkSheetViewState.Visible; // or Hidden, VeryHidden

// Configure gridlines and headers
workSheet.ShowGridLines = true;
workSheet.ShowRowColHeaders = true;

// Set zoom level for better viewing
workSheet.Zoom = 85; // 85% zoom
' Protect worksheet with password to prevent unauthorized changes
workSheet.ProtectSheet("SecurePassword123")

' Freeze panes to keep headers visible while scrolling
workSheet.CreateFreezePane(0, 1) ' Freeze first row
' workSheet.CreateFreezePane(1, 1); // Freeze first row and column

' Set worksheet visibility options
workSheet.ViewState = WorkSheetViewState.Visible ' or Hidden, VeryHidden

' Configure gridlines and headers
workSheet.ShowGridLines = True
workSheet.ShowRowColHeaders = True

' Set zoom level for better viewing
workSheet.Zoom = 85 ' 85% zoom
$vbLabelText   $csharpLabel

Worksheet protection prevents accidental modifications while freeze panes keep important rows or columns visible during scrolling.

Excel spreadsheet showing frozen header row with monthly budget data

Figure 7Frozen header row remains visible while scrolling

Excel protection dialog requiring password to modify protected worksheet

Figure 8Password protection prevents unauthorized edits

7.2. How Do I Configure Page and Print Settings?

Set up professional printing options through IronXL's :

using IronXL.Printing;

// Define print area to exclude empty cells
workSheet.SetPrintArea("A1:L12");

// Configure page orientation for wide data
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape;

// Set paper size for standard printing
workSheet.PrintSetup.PaperSize = PaperSize.A4;

// Adjust margins for better layout (in inches)
workSheet.PrintSetup.LeftMargin = 0.5;
workSheet.PrintSetup.RightMargin = 0.5;
workSheet.PrintSetup.TopMargin = 0.75;
workSheet.PrintSetup.BottomMargin = 0.75;

// Configure header and footer
workSheet.PrintSetup.HeaderMargin = 0.3;
workSheet.PrintSetup.FooterMargin = 0.3;

// Scale to fit on one page
workSheet.PrintSetup.FitToPage = true;
workSheet.PrintSetup.FitToHeight = 1;
workSheet.PrintSetup.FitToWidth = 1;

// Add print headers/footers
workSheet.Header.Center = "Monthly Budget Report";
workSheet.Footer.Left = DateTime.Now.ToShortDateString();
workSheet.Footer.Right = "Page &P of &N"; // Page numbering
using IronXL.Printing;

// Define print area to exclude empty cells
workSheet.SetPrintArea("A1:L12");

// Configure page orientation for wide data
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape;

// Set paper size for standard printing
workSheet.PrintSetup.PaperSize = PaperSize.A4;

// Adjust margins for better layout (in inches)
workSheet.PrintSetup.LeftMargin = 0.5;
workSheet.PrintSetup.RightMargin = 0.5;
workSheet.PrintSetup.TopMargin = 0.75;
workSheet.PrintSetup.BottomMargin = 0.75;

// Configure header and footer
workSheet.PrintSetup.HeaderMargin = 0.3;
workSheet.PrintSetup.FooterMargin = 0.3;

// Scale to fit on one page
workSheet.PrintSetup.FitToPage = true;
workSheet.PrintSetup.FitToHeight = 1;
workSheet.PrintSetup.FitToWidth = 1;

// Add print headers/footers
workSheet.Header.Center = "Monthly Budget Report";
workSheet.Footer.Left = DateTime.Now.ToShortDateString();
workSheet.Footer.Right = "Page &P of &N"; // Page numbering
Imports IronXL.Printing

' Define print area to exclude empty cells
workSheet.SetPrintArea("A1:L12")

' Configure page orientation for wide data
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape

' Set paper size for standard printing
workSheet.PrintSetup.PaperSize = PaperSize.A4

' Adjust margins for better layout (in inches)
workSheet.PrintSetup.LeftMargin = 0.5
workSheet.PrintSetup.RightMargin = 0.5
workSheet.PrintSetup.TopMargin = 0.75
workSheet.PrintSetup.BottomMargin = 0.75

' Configure header and footer
workSheet.PrintSetup.HeaderMargin = 0.3
workSheet.PrintSetup.FooterMargin = 0.3

' Scale to fit on one page
workSheet.PrintSetup.FitToPage = True
workSheet.PrintSetup.FitToHeight = 1
workSheet.PrintSetup.FitToWidth = 1

' Add print headers/footers
workSheet.Header.Center = "Monthly Budget Report"
workSheet.Footer.Left = DateTime.Now.ToShortDateString()
workSheet.Footer.Right = "Page &P of &N" ' Page numbering
$vbLabelText   $csharpLabel

The PrintSetup class provides comprehensive print configuration options matching Excel's print settings.

Excel print preview showing landscape orientation and A4 paper size settings

Figure 9Print preview with landscape orientation and custom margins


8. How Do I Save My Excel Workbook?

Save your workbook in various formats:

// Save as XLSX (recommended for modern Excel)
workBook.SaveAs("Budget.xlsx");

// Save as XLS for legacy compatibility
workBook.SaveAs("Budget.xls");

// Save as CSV for data exchange
workBook.SaveAsCsv("Budget.csv");

// Save as JSON for web applications
workBook.SaveAsJson("Budget.json");

// Save to stream for web downloads or cloud storage
using (var stream = new MemoryStream())
{
    workBook.SaveAs(stream);
    byte[] excelData = stream.ToArray();
    // Send to client or save to cloud
}

// Save with specific encoding for international characters
workBook.SaveAsCsv("Budget_UTF8.csv", System.Text.Encoding.UTF8);
// Save as XLSX (recommended for modern Excel)
workBook.SaveAs("Budget.xlsx");

// Save as XLS for legacy compatibility
workBook.SaveAs("Budget.xls");

// Save as CSV for data exchange
workBook.SaveAsCsv("Budget.csv");

// Save as JSON for web applications
workBook.SaveAsJson("Budget.json");

// Save to stream for web downloads or cloud storage
using (var stream = new MemoryStream())
{
    workBook.SaveAs(stream);
    byte[] excelData = stream.ToArray();
    // Send to client or save to cloud
}

// Save with specific encoding for international characters
workBook.SaveAsCsv("Budget_UTF8.csv", System.Text.Encoding.UTF8);
' Save as XLSX (recommended for modern Excel)
workBook.SaveAs("Budget.xlsx")

' Save as XLS for legacy compatibility
workBook.SaveAs("Budget.xls")

' Save as CSV for data exchange
workBook.SaveAsCsv("Budget.csv")

' Save as JSON for web applications
workBook.SaveAsJson("Budget.json")

' Save to stream for web downloads or cloud storage
Using stream = New MemoryStream()
	workBook.SaveAs(stream)
	Dim excelData() As Byte = stream.ToArray()
	' Send to client or save to cloud
End Using

' Save with specific encoding for international characters
workBook.SaveAsCsv("Budget_UTF8.csv", System.Text.Encoding.UTF8)
$vbLabelText   $csharpLabel

IronXL supports multiple export formats including XLSX, XLS, CSV, TSV, and JSON. The SaveAs method automatically determines the format from the file extension.

Summary

This tutorial demonstrated how to create Excel files in C# without Microsoft Office dependencies using IronXL. You learned essential Excel operations including workbook creation, cell manipulation, formatting, formula usage, and various save options. IronXL's intuitive API makes Excel automation straightforward for .NET developers.

For more advanced features, explore merging cells, and creating charts. Ready to use IronXL in production? Start your free trial or view licensing options.


Tutorial Quick Access

Visual Studio logo

Download this Tutorial as C# Source Code

The complete C# source code for creating Excel files is available as a Visual Studio project file.

Download

Explore this Tutorial on GitHub

The source code for this project is available in C# and VB.NET on GitHub.

Use this code as an easy way to get started with Excel file creation in just a few minutes. The project is saved as a Microsoft Visual Studio project but is compatible with any .NET IDE.

Create Excel Files in C# on GitHub
GitHub logo
API documentation icon

Read the IronXL API Reference

Explore the API Reference for IronXL, detailing all features, namespaces, classes, methods, and properties for comprehensive Excel manipulation in .NET.

View the API Reference

Questions Fréquemment Posées

Comment puis-je créer des fichiers Excel en C# sans utiliser Interop ?

Vous pouvez créer des fichiers Excel sans Interop en utilisant IronXL, qui fournit une API simple : WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX). Cette approche fonctionne sur n'importe quelle plateforme .NET sans nécessiter l'installation de Microsoft Office.

Quelles plateformes prennent en charge la création de fichiers Excel avec C# ?

IronXL prend en charge la création de fichiers Excel sur .NET 10, .NET 9, .NET 8, .NET Core, .NET Framework 4.6.2+, fonctionnant sur les environnements Windows, macOS, Linux, Docker, Azure et AWS.

Comment installer une bibliothèque C# pour la génération Excel ?

Installez IronXL via le Gestionnaire de Packages NuGet dans Visual Studio, utilisez la commande PM> Install-Package IronXL.Excel, ou téléchargez directement depuis nuget.org.

Comment créer un nouveau classeur Excel de manière programmatique ?

Créez un classeur en utilisant IronXL avec WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX), puis ajoutez des feuilles de travail en utilisant workbook.CreateWorkSheet("SheetName").

Comment puis-je définir les valeurs des cellules dans une feuille de calcul Excel en utilisant C# ?

Définissez les valeurs des cellules dans IronXL en utilisant une syntaxe intuitive : worksheet["A1"].Value = "Hello World" ou définissez des plages : worksheet["A1:A10"].Value = 100.

Puis-je appliquer du formatage aux cellules Excel de manière programmatique ?

Oui, IronXL prend en charge un formatage complet, y compris les couleurs de fond (cell.Style.SetBackgroundColor("#FF0000")), les bordures, les polices, et les formats de nombre.

Comment utiliser les formules Excel en C# ?

Appliquez les formules en utilisant la propriété Formula de IronXL : worksheet["A1"].Formula = "=SUM(B1:B10)", ou utilisez des méthodes intégrées comme range.Sum(), range.Avg().

Comment puis-je protéger une feuille de calcul Excel avec un mot de passe ?

Protégez les feuilles de calcul dans IronXL en utilisant worksheet.ProtectSheet("YourPassword") pour prévenir les modifications non autorisées.

Comment configurer les paramètres d'impression pour les fichiers Excel ?

Définissez les propriétés d'impression en utilisant le PrintSetup de IronXL : worksheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape et worksheet.SetPrintArea("A1:Z100").

Comment enregistrer un classeur Excel dans différents formats ?

Enregistrez les classeurs en utilisant la méthode SaveAs de IronXL : workbook.SaveAs("file.xlsx") pour XLSX, ou utilisez SaveAsCsv(), SaveAsJson() pour d'autres formats.

Comment remplir une feuille Excel avec des données provenant d'une base de données ?

Utilisez IronXL pour remplir les feuilles de travail en récupérant les données d'une base de données et en les définissant dans les cellules en utilisant des méthodes comme worksheet["A1"].Value = dataFromDatabase.

Comment puis-je implémenter des volets figés dans une feuille Excel en utilisant C# ?

Figez les volets dans les feuilles de travail en utilisant IronXL avec worksheet.FreezePanes(1, 1) pour verrouiller la première ligne et la première colonne pour une navigation plus facile.

Jacob Mellor, Directeur technique @ Team Iron
Directeur technique

Jacob Mellor est directeur technique chez Iron Software et un ingénieur visionnaire pionnier dans la technologie des PDF en C#. En tant que développeur original derrière la base de code principale d'Iron Software, il a façonné l'architecture du produit de l'entreprise depuis sa création, ...

Lire la suite
Prêt à commencer?
Nuget Téléchargements 1,686,155 | Version : 2025.11 vient de sortir