Passer au contenu du pied de page
UTILISATION D'IRONXL

Comment créer des rapports Excel en C# en utilisant IronXL

Creating Excel reports in C# is a fundamental requirement in modern business and .NET applications. Whether you're generating financial statements, sales analytics, or inventory dashboards, automating the process to create Excel files and Excel spreadsheets saves hours of manual effort while reducing errors.

IronXL provides a powerful, intuitive solution for developers to create an Excel report in C without requiring Microsoft Office, MS Excel, or traditional Interop dependencies. Unlike OLE Automation or approaches that rely on the Excel application, IronXL enables generating Excel workbooks and Excel data directly in code with just one line where needed. In this guide, we'll teach you how to create Excel reports with IronXl, complete with easy to follow sample code that you can easily implement into your own projects!

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

IronXL is a .NET Excel library that enables developers to create Excel, read Excel spreadsheets, and manipulate Excel files directly from C# or Visual Basic source code. Unlike Microsoft Office Interop approaches that rely on the full Excel application or reverse engineering through Open XML SDK, IronXL works across Windows, Linux, macOS, and cloud environments without requiring Excel installation or third party dependencies. This makes it ideal for server-side Excel reports, automated workflows, and web applications built on .NET Core or the .NET Framework.

For teams transitioning from manual Excel processes, older libraries, or Open XML productivity tool workflows that require navigating various XML namespaces, IronXL provides an intuitive API. It supports both legacy XLS files and modern XLSX files, which are essentially ZIP files containing XML files and various folders. Whether you want to generate a new Excel workbook, manipulate multiple worksheets, or load Excel data from external code, IronXL drastically simplifies the process without needing to understand the underlying formats.

Getting Started with IronXL to Create an Excel File

Setting up IronXL to create Excel reports takes just minutes. Install the library via NuGet Package Manager in Visual Studio:

Install-Package IronXL.Excel

Download IronXL today and start automating your Excel report generation.

Once installed, creating your first Excel report requires only a few lines of code:

using IronXL;
// Create a new Excel workbook for reports
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add a worksheet for the report
WorkSheet reportSheet = workBook.CreateWorkSheet("Monthly Report");
// Add a title
reportSheet["A1"].Value = "Sales Report - January 2024";
reportSheet["A1"].Style.Font.Bold = true;
// Save the Excel report
workBook.SaveAs("MonthlyReport.xlsx");
using IronXL;
// Create a new Excel workbook for reports
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add a worksheet for the report
WorkSheet reportSheet = workBook.CreateWorkSheet("Monthly Report");
// Add a title
reportSheet["A1"].Value = "Sales Report - January 2024";
reportSheet["A1"].Style.Font.Bold = true;
// Save the Excel report
workBook.SaveAs("MonthlyReport.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code creates a new Excel report file with a formatted title. The familiar cell reference syntax (reportSheet["A1"]) makes it easy for developers to specify exactly where data should appear, just like working with Excel manually.

Output

How to Create Excel Reports in C# Using IronXL: Figure 1 - Example Excel output

Loading Data from Multiple Sources

Real-world Excel reports rarely use static data. IronXL excels at integrating Excel data from various formats, APIs, new DataTable sources, or even several different XML files. This makes it perfect for dynamic C# Excel report generation in server-side or web applications.

Database Integration

For database-driven Excel reports, IronXL seamlessly works with ADO.NET DataTables:

using System.Data;
using System.Data.SqlClient;
// Fetch data from database
string connectionString = "Server=localhost;Database=Sales;Integrated Security=true;";
DataTable salesData = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
    SqlDataAdapter adapter = new SqlDataAdapter(
        "SELECT ProductName, Quantity, Revenue FROM MonthlySales", conn);
    adapter.Fill(salesData);
}
// Create Excel report from DataTable
WorkBook workBook = WorkBook.Create();
WorkSheet sheet = workBook.CreateWorkSheet("Sales Data");
// Add headers
sheet["A1"].Value = "Product";
sheet["B1"].Value = "Quantity";  
sheet["C1"].Value = "Revenue";
// Populate data
int row = 2;
foreach (DataRow dataRow in salesData.Rows)
{
    sheet[$"A{row}"].Value = dataRow["ProductName"];
    sheet[$"B{row}"].Value = dataRow["Quantity"];
    sheet[$"C{row}"].Value = dataRow["Revenue"];
    row++;
}
using System.Data;
using System.Data.SqlClient;
// Fetch data from database
string connectionString = "Server=localhost;Database=Sales;Integrated Security=true;";
DataTable salesData = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
    SqlDataAdapter adapter = new SqlDataAdapter(
        "SELECT ProductName, Quantity, Revenue FROM MonthlySales", conn);
    adapter.Fill(salesData);
}
// Create Excel report from DataTable
WorkBook workBook = WorkBook.Create();
WorkSheet sheet = workBook.CreateWorkSheet("Sales Data");
// Add headers
sheet["A1"].Value = "Product";
sheet["B1"].Value = "Quantity";  
sheet["C1"].Value = "Revenue";
// Populate data
int row = 2;
foreach (DataRow dataRow in salesData.Rows)
{
    sheet[$"A{row}"].Value = dataRow["ProductName"];
    sheet[$"B{row}"].Value = dataRow["Quantity"];
    sheet[$"C{row}"].Value = dataRow["Revenue"];
    row++;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This approach loads sales data directly from SQL Server into your Excel report. The DataTable integration means you can use existing data access code without modification. For more complex scenarios, check out how to load Excel from SQL databases.

Working with Collections

For in-memory data, Excel data from API responses, or a new DataTable, collections can populate Excel worksheets easily without Microsoft Excel or third party dependencies:

var salesRecords = new List<SalesRecord>
{
    new SalesRecord { Product = "Widget A", Units = 150, Price = 29.99m },
    new SalesRecord { Product = "Widget B", Units = 82, Price = 49.99m }
};
// Convert collection to Excel
for (int i = 0; i < salesRecords.Count; i++)
{
    sheet[$"A{i+2}"].Value = salesRecords[i].Product;
    sheet[$"B{i+2}"].Value = salesRecords[i].Units;
    sheet[$"C{i+2}"].Value = salesRecords[i].Price;
}
var salesRecords = new List<SalesRecord>
{
    new SalesRecord { Product = "Widget A", Units = 150, Price = 29.99m },
    new SalesRecord { Product = "Widget B", Units = 82, Price = 49.99m }
};
// Convert collection to Excel
for (int i = 0; i < salesRecords.Count; i++)
{
    sheet[$"A{i+2}"].Value = salesRecords[i].Product;
    sheet[$"B{i+2}"].Value = salesRecords[i].Units;
    sheet[$"C{i+2}"].Value = salesRecords[i].Price;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This method allows creating an Excel report in C# directly in a .NET application, making the process involved for generating multiple worksheets or XLSX files much simpler than manual OLE Automation or reverse engineering XML files.

Output

How to Create Excel Reports in C# Using IronXL: Figure 2 - Sample worksheet from data output

Formatting Professional Excel Reports

Raw data alone doesn't make a professional report. IronXL provides comprehensive cell formatting options to create polished, business-ready Excel files. The following code shows how easy this is with IronXL:

using IronXL;
using IronXL.Styles;
class Program
{
    static void Main(string[] args)
    {
        // Create a new workbook
        var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        // Add a new worksheet
        var sheet = workbook.CreateWorkSheet("MySheet");
        // Add header values
        sheet["A1"].Value = "Product";
        sheet["B1"].Value = "Quantity";
        sheet["C1"].Value = "Price";
        // Add sample data rows
        sheet["A2"].Value = "Laptop";
        sheet["B2"].Value = 5;
        sheet["C2"].Value = 1299.99;
        sheet["A3"].Value = "Headphones";
        sheet["B3"].Value = 15;
        sheet["C3"].Value = 199.50;
        sheet["A4"].Value = "Keyboard";
        sheet["B4"].Value = 10;
        sheet["C4"].Value = 89.99;
        sheet["A5"].Value = "Monitor";
        sheet["B5"].Value = 7;
        sheet["C5"].Value = 249.00;
        // Header formatting
        var headerRange = sheet["A1:C1"];
        headerRange.Style.Font.Bold = true;
        headerRange.Style.SetBackgroundColor("#4472C4");
        headerRange.Style.Font.Color = "#FFFFFF";
        headerRange.Style.BottomBorder.Type = BorderType.Thick;
        // Number formatting for currency  
        sheet["C:C"].FormatString = "$#,##0.00";
        // Alternating row colors for readability
        for (int row = 2; row <= 10; row++)
        {
            if (row % 2 == 0)
            {
                sheet[$"A{row}:C{row}"].Style.SetBackgroundColor("#F2F2F2");
            }
        }
        // Column width adjustment
        sheet.Columns[0].Width = 15 * 256; // Width in 1/256th of character width
        sheet.Columns[2].Width = 12 * 256;
        // Add borders around data
        var dataRange = sheet["A1:C10"];
        dataRange.Style.TopBorder.Type = BorderType.Thin;
        dataRange.Style.RightBorder.Type = BorderType.Thin;
        dataRange.Style.BottomBorder.Type = BorderType.Thin;
        dataRange.Style.LeftBorder.Type = BorderType.Thin;
        // Save the workbook to a file
        workbook.SaveAs("MyWorkbook.xlsx");
    }
}
using IronXL;
using IronXL.Styles;
class Program
{
    static void Main(string[] args)
    {
        // Create a new workbook
        var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        // Add a new worksheet
        var sheet = workbook.CreateWorkSheet("MySheet");
        // Add header values
        sheet["A1"].Value = "Product";
        sheet["B1"].Value = "Quantity";
        sheet["C1"].Value = "Price";
        // Add sample data rows
        sheet["A2"].Value = "Laptop";
        sheet["B2"].Value = 5;
        sheet["C2"].Value = 1299.99;
        sheet["A3"].Value = "Headphones";
        sheet["B3"].Value = 15;
        sheet["C3"].Value = 199.50;
        sheet["A4"].Value = "Keyboard";
        sheet["B4"].Value = 10;
        sheet["C4"].Value = 89.99;
        sheet["A5"].Value = "Monitor";
        sheet["B5"].Value = 7;
        sheet["C5"].Value = 249.00;
        // Header formatting
        var headerRange = sheet["A1:C1"];
        headerRange.Style.Font.Bold = true;
        headerRange.Style.SetBackgroundColor("#4472C4");
        headerRange.Style.Font.Color = "#FFFFFF";
        headerRange.Style.BottomBorder.Type = BorderType.Thick;
        // Number formatting for currency  
        sheet["C:C"].FormatString = "$#,##0.00";
        // Alternating row colors for readability
        for (int row = 2; row <= 10; row++)
        {
            if (row % 2 == 0)
            {
                sheet[$"A{row}:C{row}"].Style.SetBackgroundColor("#F2F2F2");
            }
        }
        // Column width adjustment
        sheet.Columns[0].Width = 15 * 256; // Width in 1/256th of character width
        sheet.Columns[2].Width = 12 * 256;
        // Add borders around data
        var dataRange = sheet["A1:C10"];
        dataRange.Style.TopBorder.Type = BorderType.Thin;
        dataRange.Style.RightBorder.Type = BorderType.Thin;
        dataRange.Style.BottomBorder.Type = BorderType.Thin;
        dataRange.Style.LeftBorder.Type = BorderType.Thin;
        // Save the workbook to a file
        workbook.SaveAs("MyWorkbook.xlsx");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

These formatting options transform basic data into professional reports. The style API covers everything from fonts and colors to borders and alignment, giving complete control over the Excel report appearance. For advanced formatting needs, explore conditional formatting to highlight important data automatically.

How to Create Excel Reports in C# Using IronXL: Figure 3 - Formatted Excel output

Using Formulas for Dynamic Excel Report Calculations

Excel's power lies in its formulas, and IronXL fully supports Excel formula creation:

// Add formula for row totals
sheet["D1"].Value = "Total";
sheet["D2"].Formula = "=B2*C2";
// Copy formula down the column
for (int row = 3; row <= 10; row++)
{
    sheet[$"D{row}"].Formula = $"=B{row}*C{row}";
}
// Add summary formulas
sheet["A12"].Value = "Summary";
sheet["B12"].Formula = "=SUM(B2:B10)";
sheet["C12"].Formula = "=AVERAGE(C2:C10)";
sheet["D12"].Formula = "=SUM(D2:D10)";
// Add formula for row totals
sheet["D1"].Value = "Total";
sheet["D2"].Formula = "=B2*C2";
// Copy formula down the column
for (int row = 3; row <= 10; row++)
{
    sheet[$"D{row}"].Formula = $"=B{row}*C{row}";
}
// Add summary formulas
sheet["A12"].Value = "Summary";
sheet["B12"].Formula = "=SUM(B2:B10)";
sheet["C12"].Formula = "=AVERAGE(C2:C10)";
sheet["D12"].Formula = "=SUM(D2:D10)";
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The formula support includes all standard Excel functions like SUM, AVERAGE, IF, VLOOKUP, and more. IronXL automatically handles formula dependencies and calculation order, making Excel report generation with complex calculations straightforward. Learn more about math functions in IronXL.

How to Create Excel Reports in C# Using IronXL: Figure 4 - Example output with formulas

Template-Based Reports

For recurring Excel reports or standardized workbooks, IronXL supports template-based generation, allowing developers to create an Excel file from a template without dealing with Open XML SDK, rels files, or various folders:

// Load existing template
WorkBook templateBook = WorkBook.Load("ReportTemplate.xlsx");
WorkSheet templateSheet = templateBook.DefaultWorkSheet;
// Find and replace template markers
foreach (var cell in templateSheet["A1:Z100"])
{
    if (cell.Text.Contains("{{CompanyName}}"))
        cell.Value = cell.Text.Replace("{{CompanyName}}", "Acme Corp");
    if (cell.Text.Contains("{{ReportDate}}"))
        cell.Value = cell.Text.Replace("{{ReportDate}}", DateTime.Now.ToString("MMMM yyyy"));
}
// Save as new report
templateBook.SaveAs($"Report_{DateTime.Now:yyyyMMdd}.xlsx");
// Load existing template
WorkBook templateBook = WorkBook.Load("ReportTemplate.xlsx");
WorkSheet templateSheet = templateBook.DefaultWorkSheet;
// Find and replace template markers
foreach (var cell in templateSheet["A1:Z100"])
{
    if (cell.Text.Contains("{{CompanyName}}"))
        cell.Value = cell.Text.Replace("{{CompanyName}}", "Acme Corp");
    if (cell.Text.Contains("{{ReportDate}}"))
        cell.Value = cell.Text.Replace("{{ReportDate}}", DateTime.Now.ToString("MMMM yyyy"));
}
// Save as new report
templateBook.SaveAs($"Report_{DateTime.Now:yyyyMMdd}.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This approach maintains consistent formatting while updating dynamic content, perfect for monthly reports or standardized documents.

How to Create Excel Reports in C# Using IronXL: Figure 5 - The report template vs. our Excel file created using the template

Best Practices and Troubleshooting

When implementing Excel report generation, keep these tips in mind:

  • Memory usage with large files: Process data in chunks rather than loading entire datasets (Microsoft's recommendations for large Excel files)
  • Date formatting issues: Use DateTime.ToOADate() for Excel-compatible dates (Excel date system explained)
  • File locked errors: Always properly dispose Excel objects using using statements or new MemoryStream approaches.
  • Missing styles: Some style properties require setting background color first

Conclusion

IronXL transforms Excel report generation from a tedious manual process into an automated, reliable workflow. With its intuitive API, cross-platform support, and comprehensive feature set, developers can create professional Excel reports in minutes rather than hours. The combination of easy data integration, powerful formatting options, and formula support makes IronXL an essential tool for any C# developer working with Excel reports. For developers who are interested, IronXL offers a free trial and further licensing options for companies and individuals.

Commencez avec IronXL maintenant.
green arrow pointer

Questions Fréquemment Posées

Comment puis-je créer un rapport Excel en C# ?

Vous pouvez créer un rapport Excel en C# en utilisant la bibliothèque IronXL, qui simplifie le processus de génération de fichiers Excel avec des fonctionnalités telles que la mise en forme, les formules et l'intégration de base de données.

Quels sont les avantages d'utiliser IronXL pour générer des rapports Excel ?

IronXL offre un moyen efficace d'automatiser la génération de rapports Excel, réduisant l'effort manuel et minimisant les erreurs. Il prend en charge une variété de fonctionnalités telles que la mise en forme avancée, les calculs de formules et une intégration transparente avec les bases de données.

Est-il possible d'intégrer des bases de données lors de la création de rapports Excel avec IronXL ?

Oui, IronXL permet une intégration facile avec les bases de données, vous permettant de récupérer les données directement de votre base de données à vos rapports Excel.

Puis-je appliquer une mise en forme personnalisée aux rapports Excel en utilisant IronXL ?

Absolument, IronXL prend en charge la mise en forme personnalisée, vous permettant de styliser vos rapports Excel avec des polices, des couleurs et des styles de cellules spécifiques pour répondre aux normes professionnelles.

IronXL prend-il en charge les calculs de formules dans les rapports Excel ?

Oui, IronXL prend en charge l'utilisation de formules dans les rapports Excel, permettant des calculs et des analyses de données directement dans vos fichiers Excel générés.

Pourquoi devrais-je automatiser la génération de rapports Excel dans mon application .NET ?

L'automatisation de la génération de rapports Excel dans votre application .NET permet de gagner du temps, de réduire les erreurs humaines et d'augmenter la productivité en éliminant les tâches répétitives impliquées dans la création manuelle de rapports.

IronXL peut-il gérer de grands ensembles de données lors de la création de rapports Excel ?

IronXL est conçu pour gérer efficacement de grands ensembles de données, ce qui le rend idéal pour générer des rapports Excel nécessitant le traitement de quantités importantes de données.

Quels types de rapports Excel puis-je créer en utilisant IronXL ?

Avec IronXL, vous pouvez créer divers types de rapports Excel, tels que des états financiers, des analyses de ventes, des tableaux de bord d'inventaire, et plus encore, adaptés à vos besoins commerciaux spécifiques.

Comment IronXL aide-t-il à réduire l'effort manuel dans la création de rapports Excel ?

IronXL automatise le processus de création de rapports en générant des fichiers Excel de manière programmatique, ce qui réduit considérablement l'effort manuel impliqué dans la mise en forme, la saisie de données et les calculs.

IronXL est-il adapté pour créer des rapports Excel professionnels ?

Oui, IronXL convient à la création de rapports Excel professionnels, offrant une gamme de fonctionnalités qui garantissent que vos rapports soient bien mis en forme, précis et prêts pour une utilisation professionnelle.

Jordi Bardia
Ingénieur logiciel
Jordi est le plus compétent en Python, C# et C++, et lorsqu'il ne met pas à profit ses compétences chez Iron Software, il programme des jeux. Partageant les responsabilités des tests de produit, du développement de produit et de la recherche, Jordi apporte une immense valeur à l'amé...
Lire la suite