Jak tworzyć raporty Excel w języku C# za pomocą IronXL
Creating Excel Reports in C# with 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, read Excel spreadsheets, and manipulate Excel files directly from C# or Visual Basic source code. W przeciwieństwie do rozwiązań Microsoft Office Interop, które opierają się na pełnej aplikacji Excel lub inżynierii odwrotnej za pomocą Open XML SDK, IronXL działa w systemach Windows, Linux, macOS oraz w środowiskach chmurowych bez konieczności instalacji programu Excel lub zależności od oprogramowania innych firm. Dzięki temu idealnie nadaje się do raportów Excel po stronie serwera, zautomatyzowanych przepływów pracy oraz aplikacji internetowych zbudowanych na platformie .NET Core lub .NET Framework.
Dla zespołów przechodzących z ręcznych procesów w Excelu, starszych bibliotek lub przepływów pracy w narzędziach biurowych Open XML, które wymagają poruszania się po różnych przestrzeniach nazw XML, IronXL zapewnia intuicyjny interfejs API. Obsługuje zarówno starsze pliki XLS, jak i nowoczesne pliki XLSX, które są w zasadzie plikami ZIP zawierającymi pliki XML i różne foldery. 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
Konfiguracja IronXL do tworzenia raportów w Excelu zajmuje zaledwie kilka minut. Install the library via NuGet Package Manager in Visual Studio:
Install-Package IronXl.Excel
Download IronXL today and start automating your Excel report generation.
Po zainstalowaniu utworzenie pierwszego raportu w Excelu wymaga zaledwie kilku wierszy kodu:
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");
Imports IronXL
' Create a new Excel workbook for reports
Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
' Add a worksheet for the report
Dim reportSheet As WorkSheet = 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")
Ten kod tworzy nowy plik raportu Excel z sformatowanym tytułem. 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.
Wynik

Loading Data from Multiple Sources
W rzeczywistych raportach Excel rzadko wykorzystuje się dane statyczne. IronXL excels at integrating Excel data from various formats, APIs, new DataTable sources, or even several different XML files. Dzięki temu idealnie nadaje się do dynamicznego generowania raportów w formacie Excel w języku C# w aplikacjach serwerowych lub internetowych.
Integracja baz danych
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++;
}
Imports System.Data
Imports System.Data.SqlClient
' Fetch data from database
Dim connectionString As String = "Server=localhost;Database=Sales;Integrated Security=true;"
Dim salesData As New DataTable()
Using conn As New SqlConnection(connectionString)
Dim adapter As New SqlDataAdapter("SELECT ProductName, Quantity, Revenue FROM MonthlySales", conn)
adapter.Fill(salesData)
End Using
' Create Excel report from DataTable
Dim workBook As WorkBook = WorkBook.Create()
Dim sheet As WorkSheet = workBook.CreateWorkSheet("Sales Data")
' Add headers
sheet("A1").Value = "Product"
sheet("B1").Value = "Quantity"
sheet("C1").Value = "Revenue"
' Populate data
Dim row As Integer = 2
For Each dataRow As DataRow In salesData.Rows
sheet($"A{row}").Value = dataRow("ProductName")
sheet($"B{row}").Value = dataRow("Quantity")
sheet($"C{row}").Value = dataRow("Revenue")
row += 1
Next
To podejście ładuje dane sprzedażowe bezpośrednio z serwera SQL do raportu w programie Excel. Integracja z DataTable oznacza, że można korzystać z istniejącego kodu dostępu do danych bez konieczności wprowadzania zmian. 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;
}
Imports System.Collections.Generic
Dim salesRecords As New List(Of SalesRecord) From {
New SalesRecord With {.Product = "Widget A", .Units = 150, .Price = 29.99D},
New SalesRecord With {.Product = "Widget B", .Units = 82, .Price = 49.99D}
}
' Convert collection to Excel
For i As Integer = 0 To salesRecords.Count - 1
sheet($"A{i + 2}").Value = salesRecords(i).Product
sheet($"B{i + 2}").Value = salesRecords(i).Units
sheet($"C{i + 2}").Value = salesRecords(i).Price
Next
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.
Wynik

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");
}
}
Imports IronXL
Imports IronXl.Styles
Module Program
Sub Main(args As String())
' Create a new workbook
Dim workbook = WorkBook.Create(ExcelFileFormat.XLSX)
' Add a new worksheet
Dim 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.5
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.0
' Header formatting
Dim 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 row As Integer = 2 To 10
If row Mod 2 = 0 Then
sheet($"A{row}:C{row}").Style.SetBackgroundColor("#F2F2F2")
End If
Next
' 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
Dim 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")
End Sub
End Module
Te opcje formatowania przekształcają podstawowe dane w profesjonalne raporty. 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.

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)";
' Add formula for row totals
sheet("D1").Value = "Total"
sheet("D2").Formula = "=B2*C2"
' Copy formula down the column
For row As Integer = 3 To 10
sheet($"D{row}").Formula = $"=B{row}*C{row}"
Next
' 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)"
The formula support includes all standard Excel functions like SUM, AVERAGE, IF, VLOOKUP, and more. IronXL automatycznie obsługuje zależności między formułami i kolejność obliczeń, dzięki czemu generowanie raportów w Excelu zawierających złożone obliczenia staje się proste. Learn more about math functions in IronXL.

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");
Imports System
' Load existing template
Dim templateBook As Workbook = Workbook.Load("ReportTemplate.xlsx")
Dim templateSheet As Worksheet = templateBook.DefaultWorksheet
' Find and replace template markers
For Each cell In templateSheet("A1:Z100")
If cell.Text.Contains("{{CompanyName}}") Then
cell.Value = cell.Text.Replace("{{CompanyName}}", "Acme Corp")
End If
If cell.Text.Contains("{{ReportDate}}") Then
cell.Value = cell.Text.Replace("{{ReportDate}}", DateTime.Now.ToString("MMMM yyyy"))
End If
Next
' Save as new report
templateBook.SaveAs($"Report_{DateTime.Now:yyyyMMdd}.xlsx")
This approach maintains consistent formatting while updating dynamic content, perfect for monthly reports or standardized documents.

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
usingstatements or newMemoryStreamapproaches. - Missing styles: Some style properties require setting background color first
Wnioski
IronXL zmienia generowanie raportów w Excelu z żmudnego, ręcznego procesu w zautomatyzowany, niezawodny przepływ pracy. With its intuitive API, cross-platform support, and comprehensive feature set, developers can create professional Excel reports in minutes rather than hours. Połączenie łatwej integracji danych, rozbudowanych opcji formatowania i obsługi formuł sprawia, że IronXL jest niezbędnym narzędziem dla każdego programisty C# pracującego z raportami Excel. For developers who are interested, IronXL offers a free trial and further licensing options for companies and individuals.
Często Zadawane Pytania
Do czego służy IronXL w języku C#?
IronXL to potężna biblioteka dla języka C#, która umożliwia programistom łatwe tworzenie, edytowanie i odczytywanie plików Excel. Obsługuje generowanie profesjonalnych raportów Excel z zaawansowanym formatowaniem, formułami i integracją danych.
Jak mogę tworzyć raporty w Excelu za pomocą IronXL?
Aby tworzyć raporty w Excelu przy użyciu IronXL, można wykorzystać jego rozbudowane API do dodawania danych, formatowania komórek, stosowania formuł i integracji z bazami danych, a wszystko to w środowisku C#.
Jakie funkcje oferuje IronXL do generowania raportów w Excelu?
IronXL oferuje funkcje takie jak formatowanie komórek, stosowanie formuł, walidacja danych, tworzenie wykresów oraz płynną integrację z bazami danych, umożliwiając kompleksowe generowanie raportów w Excelu.
Czy IronXL obsługuje integrację z bazami danych?
Tak, IronXL obsługuje integrację z bazami danych, umożliwiając pobieranie danych bezpośrednio z baz danych i włączanie ich do raportów Excel, usprawniając analizę danych i raportowanie.
Czy IronXL radzi sobie ze złożonymi formułami w Excelu?
IronXL obsługuje szeroki zakres formuł programu Excel, umożliwiając programistom wykonywanie złożonych obliczeń i automatyzację przetwarzania danych w raportach programu Excel.
Czy za pomocą IronXL można formatować komórki w Excelu?
IronXL oferuje szerokie możliwości formatowania, pozwalając dostosować wygląd komórek, w tym styl czcionki, kolor, obramowania i inne elementy, aby tworzyć atrakcyjne wizualnie raporty w Excelu.
Czy mogę tworzyć wykresy w Excelu za pomocą IronXL?
Tak, IronXL pozwala tworzyć różnorodne wykresy w arkuszach kalkulacyjnych Excel, pomagając w wizualnej prezentacji danych i zwiększając czytelność raportów.
W jaki sposób IronXL upraszcza proces generowania raportów w Excelu?
IronXL upraszcza proces generowania raportów w Excelu, oferując kompleksowy zestaw funkcji usprawniających wprowadzanie danych, formatowanie, obliczenia i generowanie wyników — wszystko w środowisku programistycznym C#.
Czy IronXL może efektywnie obsługiwać duże zbiory danych?
IronXL jest zoptymalizowany pod kątem wydajności, co pozwala mu efektywnie obsługiwać duże zbiory danych, dzięki czemu idealnie nadaje się do generowania złożonych raportów bez utraty szybkości lub niezawodności.
Dla jakiego języka programowania został zaprojektowany IronXL?
IronXL został zaprojektowany specjalnie do użytku z językiem C#, zapewniając płynną integrację i funkcjonalność dla programistów pracujących w środowisku .NET Framework.




