跳至页脚内容
使用 IRONXL

如何使用IronXL在 C# 中生成 Excel 文件

传统上,使用 C# 以编程方式生成 Excel 工作表文件需要安装 Microsoft Office 或进行复杂的 COM 互操作IronXL彻底改变了这一现状,提供了一个简单的 API,无需任何 Office 依赖即可创建 Excel 文件。 本教程将引导您使用 IronXL.Excel 在 C# 中构建 Excel 文件,从基本的电子表格创建到高级格式化和数据库集成。 无论您是创建报告、导出数据(XLS 或 XLSX 文件)还是自动生成电子表格,您都将学习在.NET应用程序中使用 Excel的基本技巧。

如何使用 IronXL 在 C# 中生成 Excel 文件:图 1 - IronXL

为何无需 Microsoft Office 即可生成 Excel 文件?

在不依赖 Office 的情况下开发 Excel 生成功能,解决了关键的部署难题。 由于许可成本和资源开销,服务器环境很少安装 Microsoft Office。 每次安装 Office 都需要大量的磁盘空间和内存,因此对于云部署或容器化应用程序来说并不实用。

IronXL通过独立运行消除了这些限制。 您的 C# Excel 文件生成可在 Windows、Linux、macOS、Docker 容器或 Azure 应用服务上运行,无需修改。 这种跨平台兼容性意味着您只需编写一次代码,即可部署到任何地方,无论是面向.NET Framework、 .NET Core还是.NET 10 应用程序。

如何使用 IronXL 在 C# 中生成 Excel 文件:图 2 - 跨平台

性能显著提高,无需 COM Interop 开销。 传统的办公自动化会为每个操作创建单独的进程实例,从而消耗内存和 CPU 资源。 IronXL在应用程序进程空间内的内存中处理所有内容,从而在以编程方式生成 Excel 文件时实现更快的执行速度和更低的资源消耗。

由于 IronXL 以一个 NuGet 包的形式发布,因此部署变得非常简单。 无需注册表项、无需 COM 注册、无需维护 Office 服务包。 您的持续集成管道运行顺畅,Docker 容器保持轻量级。 这种简化方法使 IronXL 大受欢迎,在各种 开发人员论坛上,专业人士分享了他们在 Excel 自动化方面的经验。

一些开发人员仍然在探索微软的 Open XML Productivity Tool,以便直接处理 Office Open XML 文件结构。 不过,这种方法需要更多的人工努力,以及对 XML 架构和 Open XML SDK 安装的详细了解。 IronXL 消除了这些复杂性,让您能够更快地以编程方式使用 Excel。

如何使用 IronXL 在 C# 中生成 Excel 文件:图 3 - 功能

如何在 C# 项目中安装IronXL ?

通过 Visual Studio 中的NuGet包管理器安装IronXL只需几分钟。 在解决方案资源管理器中右键单击您的项目,然后选择"管理NuGet程序包"。搜索"IronXL.Excel",然后单击"安装"。 该软件包自动包含用 C# 生成 Excel 文件所需的所有依赖项。

要通过程序包管理器控制台或.NET CLI 进行安装,请使用以下任一命令:

Install-Package IronXL.Excel
dotnet add package IronXL.Excel
Install-Package IronXL.Excel
dotnet add package IronXL.Excel
SHELL

如何使用 IronXL 在 C# 中生成 Excel 文件:图 4 - 安装

使用以下简单测试验证安装是否已就绪:

using IronXL;
// Create an in-memory workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");
using IronXL;
// Create an in-memory workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");
Imports IronXL

' Create an in-memory workbook
Dim workbook = WorkBook.Create()
Console.WriteLine("IronXL installed successfully!")
$vbLabelText   $csharpLabel

如果运行没有错误, IronXL即可使用。 该库支持所有现代 .NET 版本,确保与您现有的项目兼容。 有关详细的安装指南和故障排除,请参阅官方NuGet安装文档

输出

如何使用 IronXL 在 C# 中生成 Excel 文件:图 5 - 控制台输出

如何创建你的第一个Excel文件?

使用IronXL创建 Excel 文件首先要从 WorkBook 类开始,它是您进行所有 Excel 操作的入口。 该库同时支持现代 XLSX 和旧式 XLS 格式,让您在 C# 中创建 Excel 文件时能够灵活满足不同的需求。

using IronXL;
// Create a new workbook (XLSX format by default)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add metadata
workbook.Metadata.Title = "Monthly Sales Report";
workbook.Metadata.Author = "Sales Department";
workbook.Metadata.Comments = "Generated using IronXL";
// Create a worksheet
WorkSheet worksheet = workbook.CreateWorkSheet("January Sales");
// Add header row
worksheet["A1"].Value = "Date";
worksheet["B1"].Value = "Product";
worksheet["C1"].Value = "Quantity";
worksheet["D1"].Value = "Revenue";
// Add data rows
worksheet["A2"].Value = new DateTime(2024, 1, 15);
worksheet["B2"].Value = "Widget Pro";
worksheet["C2"].Value = 100;
worksheet["D2"].Value = 2500.00;
// Save the workbook
workbook.SaveAs("FirstExcelFile.xlsx");
using IronXL;
// Create a new workbook (XLSX format by default)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add metadata
workbook.Metadata.Title = "Monthly Sales Report";
workbook.Metadata.Author = "Sales Department";
workbook.Metadata.Comments = "Generated using IronXL";
// Create a worksheet
WorkSheet worksheet = workbook.CreateWorkSheet("January Sales");
// Add header row
worksheet["A1"].Value = "Date";
worksheet["B1"].Value = "Product";
worksheet["C1"].Value = "Quantity";
worksheet["D1"].Value = "Revenue";
// Add data rows
worksheet["A2"].Value = new DateTime(2024, 1, 15);
worksheet["B2"].Value = "Widget Pro";
worksheet["C2"].Value = 100;
worksheet["D2"].Value = 2500.00;
// Save the workbook
workbook.SaveAs("FirstExcelFile.xlsx");
Imports IronXL

' Create a new workbook (XLSX format by default)
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

' Add metadata
workbook.Metadata.Title = "Monthly Sales Report"
workbook.Metadata.Author = "Sales Department"
workbook.Metadata.Comments = "Generated using IronXL"

' Create a worksheet
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("January Sales")

' Add header row
worksheet("A1").Value = "Date"
worksheet("B1").Value = "Product"
worksheet("C1").Value = "Quantity"
worksheet("D1").Value = "Revenue"

' Add data rows
worksheet("A2").Value = New DateTime(2024, 1, 15)
worksheet("B2").Value = "Widget Pro"
worksheet("C2").Value = 100
worksheet("D2").Value = 2500.0

' Save the workbook
workbook.SaveAs("FirstExcelFile.xlsx")
$vbLabelText   $csharpLabel

这段代码演示了 Excel 文件生成的几个关键概念。 WorkBook.Create() 方法在内存中初始化一个新的 Excel 文件。 您可以使用 ExcelFileFormat 枚举指定格式 -- 选择 XLSX 可兼容现代 Excel,选择 XLS 可支持旧版 Excel。 Metadata 属性允许您嵌入文档信息,该信息将出现在 Excel 的文件属性中,遵循Microsoft 的文档属性标准

CreateWorkSheet() 方法会添加一个具有指定名称的新工作表。 Excel 熟悉的单元格符号(A1、B1 等)使数值设置更加直观。IronXL 可自动处理数据类型转换,无需显式转换即可识别日期、数字和文本。 SaveAs() 方法将整个 Excel 文件写入磁盘。 如需了解更多工作表操作,请参阅如何编写 Excel 文件指南

输出

如何使用 IronXL 在 C# 中生成 Excel 文件:图 6 - 基本 Excel 输出

如何将数据写入Excel单元格?

IronXL.Excel 提供了多种填充 Excel 单元格的方法,从单个单元格赋值到批量范围操作。 了解这些方法有助于您在向 Excel 文件写入数据时,根据您的数据场景选择最有效的方法。

using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Individual cell assignment
worksheet["A1"].Value = "Employee Name";
worksheet["A2"].Value = "John Smith";
worksheet["A3"].Value = "Jane Doe";
// Range assignment for multiple cells at once
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based row, 0-based column)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales");       // C2
worksheet.SetCellValue(2, 2, "Marketing");   // C3
// Array-based header population
string[] headers = { "ID", "Name", "Email", "Phone" };
for (int i = 0; i < headers.Length; i++)
{
    worksheet.SetCellValue(0, i, headers[i]);
}
// Working with different data types
worksheet["E1"].Value = "Salary";
worksheet["E2"].Value = 75000.50m;  // Decimal for currency
worksheet["E3"].Value = 82000.75m;
worksheet["F1"].Value = "Start Date";
worksheet["F2"].Value = new DateTime(2020, 3, 15);
worksheet["F3"].Value = new DateTime(2019, 7, 1);
worksheet["G1"].Value = "Full Time";
worksheet["G2"].Value = true;  // Boolean
worksheet["G3"].Value = true;
workbook.SaveAs("EmployeeData.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Individual cell assignment
worksheet["A1"].Value = "Employee Name";
worksheet["A2"].Value = "John Smith";
worksheet["A3"].Value = "Jane Doe";
// Range assignment for multiple cells at once
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based row, 0-based column)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales");       // C2
worksheet.SetCellValue(2, 2, "Marketing");   // C3
// Array-based header population
string[] headers = { "ID", "Name", "Email", "Phone" };
for (int i = 0; i < headers.Length; i++)
{
    worksheet.SetCellValue(0, i, headers[i]);
}
// Working with different data types
worksheet["E1"].Value = "Salary";
worksheet["E2"].Value = 75000.50m;  // Decimal for currency
worksheet["E3"].Value = 82000.75m;
worksheet["F1"].Value = "Start Date";
worksheet["F2"].Value = new DateTime(2020, 3, 15);
worksheet["F3"].Value = new DateTime(2019, 7, 1);
worksheet["G1"].Value = "Full Time";
worksheet["G2"].Value = true;  // Boolean
worksheet["G3"].Value = true;
workbook.SaveAs("EmployeeData.xlsx");
Imports IronXL

Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("Employees")
' Individual cell assignment
worksheet("A1").Value = "Employee Name"
worksheet("A2").Value = "John Smith"
worksheet("A3").Value = "Jane Doe"
' Range assignment for multiple cells at once
worksheet("B1:B3").Value = "Active"
' Using numeric indices (0-based row, 0-based column)
worksheet.SetCellValue(0, 2, "Department") ' C1
worksheet.SetCellValue(1, 2, "Sales") ' C2
worksheet.SetCellValue(2, 2, "Marketing") ' C3
' Array-based header population
Dim headers As String() = {"ID", "Name", "Email", "Phone"}
For i As Integer = 0 To headers.Length - 1
    worksheet.SetCellValue(0, i, headers(i))
Next
' Working with different data types
worksheet("E1").Value = "Salary"
worksheet("E2").Value = 75000.5D ' Decimal for currency
worksheet("E3").Value = 82000.75D
worksheet("F1").Value = "Start Date"
worksheet("F2").Value = New DateTime(2020, 3, 15)
worksheet("F3").Value = New DateTime(2019, 7, 1)
worksheet("G1").Value = "Full Time"
worksheet("G2").Value = True ' Boolean
worksheet("G3").Value = True
workbook.SaveAs("EmployeeData.xlsx")
$vbLabelText   $csharpLabel

代码显示了 IronXL 灵活的单元格寻址。 字符串符号("A1")让 Excel 用户感觉很自然,而数字索引则为循环和动态生成提供了程序控制。 范围赋值("B1:B3")可以有效地将多个单元格设置为相同的值,非常适合初始化列或应用默认值。

IronXL 能智能地处理不同的数据类型。小数能保持财务数据的精度,DateTime 对象能正确格式化为 Excel 日期,布尔值显示为 TRUE/FALSE。 这种自动转换消除了手动格式化代码,同时确保了数据的完整性。 对于大型数据集,请查阅导入数据指南以了解更多模式。

输出

如何使用 IronXL 在 C# 中生成 Excel 文件:图 7 - Excel 输出

如何对Excel文件应用Professional格式?

专业 Excel 文件需要的不仅仅是原始数据。 IronXL 的样式 API 通过格式、颜色和视觉层次结构,将普通的电子表格转换为精美的商业文档。 您可以通过设置单元格格式来控制电子表格的各个视觉方面。

using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Header formatting
var headerRange = worksheet["A1:D1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.Font.Height = 12;
headerRange.Style.SetBackgroundColor("#4472C4");
headerRange.Style.Font.Color = "#FFFFFF";
// Column width adjustment
worksheet.AutoSizeColumn(0); // Auto-fit column A
worksheet.GetColumn(1).Width = 20; // Set column B width
// Number formatting
var salaryColumn = worksheet["E2:E3"];
salaryColumn.FormatString = "$#,##0.00";
// Date formatting
var dateColumn = worksheet["F2:F3"];
dateColumn.FormatString = "MM/dd/yyyy";
// Cell borders
var dataRange = worksheet["A1:G3"];
dataRange.Style.TopBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.LeftBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.RightBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.TopBorder.Color = "#000000";
dataRange.Style.BottomBorder.Color = "#000000";
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability (banded rows)
for (int row = 2; row <= 10; row++)
{
    if (row % 2 == 0)
    {
        worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
workbook.SaveAs("FormattedReport.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Header formatting
var headerRange = worksheet["A1:D1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.Font.Height = 12;
headerRange.Style.SetBackgroundColor("#4472C4");
headerRange.Style.Font.Color = "#FFFFFF";
// Column width adjustment
worksheet.AutoSizeColumn(0); // Auto-fit column A
worksheet.GetColumn(1).Width = 20; // Set column B width
// Number formatting
var salaryColumn = worksheet["E2:E3"];
salaryColumn.FormatString = "$#,##0.00";
// Date formatting
var dateColumn = worksheet["F2:F3"];
dateColumn.FormatString = "MM/dd/yyyy";
// Cell borders
var dataRange = worksheet["A1:G3"];
dataRange.Style.TopBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.LeftBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.RightBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.TopBorder.Color = "#000000";
dataRange.Style.BottomBorder.Color = "#000000";
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability (banded rows)
for (int row = 2; row <= 10; row++)
{
    if (row % 2 == 0)
    {
        worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
workbook.SaveAs("FormattedReport.xlsx");
Imports IronXL

Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("Employees")

' Header formatting
Dim headerRange = worksheet("A1:D1")
headerRange.Style.Font.Bold = True
headerRange.Style.Font.Height = 12
headerRange.Style.SetBackgroundColor("#4472C4")
headerRange.Style.Font.Color = "#FFFFFF"

' Column width adjustment
worksheet.AutoSizeColumn(0) ' Auto-fit column A
worksheet.GetColumn(1).Width = 20 ' Set column B width

' Number formatting
Dim salaryColumn = worksheet("E2:E3")
salaryColumn.FormatString = "$#,##0.00"

' Date formatting
Dim dateColumn = worksheet("F2:F3")
dateColumn.FormatString = "MM/dd/yyyy"

' Cell borders
Dim dataRange = worksheet("A1:G3")
dataRange.Style.TopBorder.Type = IronXL.Styles.BorderType.Thin
dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin
dataRange.Style.LeftBorder.Type = IronXL.Styles.BorderType.Thin
dataRange.Style.RightBorder.Type = IronXL.Styles.BorderType.Thin
dataRange.Style.TopBorder.Color = "#000000"
dataRange.Style.BottomBorder.Color = "#000000"

' Text alignment
worksheet("A1:G1").Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center

' Alternating row colors for readability (banded rows)
For row As Integer = 2 To 10
    If row Mod 2 = 0 Then
        worksheet($"A{row}:G{row}").Style.SetBackgroundColor("#F2F2F2")
    End If
Next

workbook.SaveAs("FormattedReport.xlsx")
$vbLabelText   $csharpLabel

这种格式化代码可以创建符合商业标准的Professional外观。 带有背景颜色的粗体标题建立了视觉层次。 SetBackgroundColor() 方法接受十六进制颜色代码,从而可以精确控制配色方案。 字体属性包括大小、颜色、粗体、斜体和下划线选项——所有这些对于创建符合公司品牌指南的 Excel 文件都至关重要。

列宽调整可防止文本截断。 AutoSizeColumn() 自动适应内容,而 GetColumn().Width 提供精确控制。 数字格式设置使用 Excel 的格式代码——例如,"$#,##0.00"表示以千位分隔符和两位小数显示货币。 日期格式遵循类似的模式,使用微软数字格式代码参考中记录的标准 Excel 日期格式字符串。

边框定义数据边界,提高可读性。 BorderType 枚举提供了各种样式:细线、中线、粗线、点线和虚线。 交替的行列颜色通常被称为 "带状行列",有助于读者在宽泛的数据集中追踪信息。 要了解有关合并单元格和其他布局功能的更多信息,请参阅合并单元格指南

输出

如何使用 IronXL 在 C# 中生成 Excel 文件:图 8 - 格式化的 Excel 输出

如何以编程方式使用Excel公式?

Excel 公式通过自动计算使电子表格栩栩如生。 IronXL 支持公式创建和评估,可实现自动更新的动态电子表格。

using IronXL;
var workbook = WorkBook.Create();
// Create a budget worksheet
WorkSheet budget = workbook.CreateWorkSheet("Q1 Budget");
// Headers
budget["A1"].Value = "Category";
budget["B1"].Value = "January";
budget["C1"].Value = "February";
budget["D1"].Value = "March";
budget["E1"].Value = "Q1 Total";
// Budget categories and values
string[] categories = { "Salaries", "Marketing", "Operations", "Equipment", "Training" };
decimal[,] monthlyBudgets = {
    { 50000, 52000, 51000 },
    { 15000, 18000, 20000 },
    { 8000, 8500, 9000 },
    { 12000, 5000, 7000 },
    { 3000, 3500, 4000 }
};
// Populate data and add row total formulas
for (int i = 0; i < categories.Length; i++)
{
    budget[$"A{i + 2}"].Value = categories[i];
    budget[$"B{i + 2}"].Value = monthlyBudgets[i, 0];
    budget[$"C{i + 2}"].Value = monthlyBudgets[i, 1];
    budget[$"D{i + 2}"].Value = monthlyBudgets[i, 2];
    budget[$"E{i + 2}"].Formula = $"=SUM(B{i + 2}:D{i + 2})";
}
// Monthly totals row
budget["A7"].Value = "Monthly Total";
budget["B7"].Formula = "=SUM(B2:B6)";
budget["C7"].Formula = "=SUM(C2:C6)";
budget["D7"].Formula = "=SUM(D2:D6)";
budget["E7"].Formula = "=SUM(E2:E6)";
// Calculate percentages
budget["A9"].Value = "Marketing %";
budget["B9"].Formula = "=B3/B7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas before saving
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");
using IronXL;
var workbook = WorkBook.Create();
// Create a budget worksheet
WorkSheet budget = workbook.CreateWorkSheet("Q1 Budget");
// Headers
budget["A1"].Value = "Category";
budget["B1"].Value = "January";
budget["C1"].Value = "February";
budget["D1"].Value = "March";
budget["E1"].Value = "Q1 Total";
// Budget categories and values
string[] categories = { "Salaries", "Marketing", "Operations", "Equipment", "Training" };
decimal[,] monthlyBudgets = {
    { 50000, 52000, 51000 },
    { 15000, 18000, 20000 },
    { 8000, 8500, 9000 },
    { 12000, 5000, 7000 },
    { 3000, 3500, 4000 }
};
// Populate data and add row total formulas
for (int i = 0; i < categories.Length; i++)
{
    budget[$"A{i + 2}"].Value = categories[i];
    budget[$"B{i + 2}"].Value = monthlyBudgets[i, 0];
    budget[$"C{i + 2}"].Value = monthlyBudgets[i, 1];
    budget[$"D{i + 2}"].Value = monthlyBudgets[i, 2];
    budget[$"E{i + 2}"].Formula = $"=SUM(B{i + 2}:D{i + 2})";
}
// Monthly totals row
budget["A7"].Value = "Monthly Total";
budget["B7"].Formula = "=SUM(B2:B6)";
budget["C7"].Formula = "=SUM(C2:C6)";
budget["D7"].Formula = "=SUM(D2:D6)";
budget["E7"].Formula = "=SUM(E2:E6)";
// Calculate percentages
budget["A9"].Value = "Marketing %";
budget["B9"].Formula = "=B3/B7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas before saving
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");
Imports IronXL

Dim workbook = WorkBook.Create()
' Create a budget worksheet
Dim budget As WorkSheet = workbook.CreateWorkSheet("Q1 Budget")
' Headers
budget("A1").Value = "Category"
budget("B1").Value = "January"
budget("C1").Value = "February"
budget("D1").Value = "March"
budget("E1").Value = "Q1 Total"
' Budget categories and values
Dim categories As String() = {"Salaries", "Marketing", "Operations", "Equipment", "Training"}
Dim monthlyBudgets As Decimal(,) = {
    {50000, 52000, 51000},
    {15000, 18000, 20000},
    {8000, 8500, 9000},
    {12000, 5000, 7000},
    {3000, 3500, 4000}
}
' Populate data and add row total formulas
For i As Integer = 0 To categories.Length - 1
    budget($"A{i + 2}").Value = categories(i)
    budget($"B{i + 2}").Value = monthlyBudgets(i, 0)
    budget($"C{i + 2}").Value = monthlyBudgets(i, 1)
    budget($"D{i + 2}").Value = monthlyBudgets(i, 2)
    budget($"E{i + 2}").Formula = $"=SUM(B{i + 2}:D{i + 2})"
Next
' Monthly totals row
budget("A7").Value = "Monthly Total"
budget("B7").Formula = "=SUM(B2:B6)"
budget("C7").Formula = "=SUM(C2:C6)"
budget("D7").Formula = "=SUM(D2:D6)"
budget("E7").Formula = "=SUM(E2:E6)"
' Calculate percentages
budget("A9").Value = "Marketing %"
budget("B9").Formula = "=B3/B7*100"
' Average calculation
budget("A10").Value = "Average Spending"
budget("B10").Formula = "=AVERAGE(B2:B6)"
' Evaluate all formulas before saving
workbook.EvaluateAll()
workbook.SaveAs("Budget.xlsx")
$vbLabelText   $csharpLabel

本预算示例说明了公式的实际应用。 Formula 属性接受以等号开头的标准 Excel 公式语法。 IronXL 支持常用函数:SUM、AVERAGE、COUNT、MAX、MIN 等。 公式中的单元格引用与 Excel 完全相同,包括相对引用和绝对引用。

EvaluateAll() 方法处理所有公式,更新整个工作簿中的计算值。 这样可以确保在 Excel 中打开文件时,公式能够显示结果。 如果不进行评估,Excel 将显示公式文本,直到用户触发重新计算。 有关读取公式结果的更多信息,请参阅读取 Excel 文件文档

输出

如何使用 IronXL 在 C# 中生成 Excel 文件:图 9 - 使用公式输出 Excel 文件

如何将数据库数据导出到Excel?

现实世界中的应用程序通常会将数据库数据导出到 Excel 中,用于报告和分析。 IronXL 通过内置的 DataTable 支持,使此过程变得简单,从 C# 应用程序导出 Excel时无需手动进行字段映射。

using System.Data;
using IronXL;

// Simulate database retrieval (replace with actual database code)
DataTable GetSalesData()
{
    DataTable dt = new DataTable("Sales");
    dt.Columns.Add("OrderID", typeof(int));
    dt.Columns.Add("CustomerName", typeof(string));
    dt.Columns.Add("Product", typeof(string));
    dt.Columns.Add("Quantity", typeof(int));
    dt.Columns.Add("UnitPrice", typeof(decimal));
    dt.Columns.Add("OrderDate", typeof(DateTime));
    dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99m, DateTime.Now.AddDays(-5));
    dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99m, DateTime.Now.AddDays(-4));
    dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99m, DateTime.Now.AddDays(-3));
    dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99m, DateTime.Now.AddDays(-2));
    dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99m, DateTime.Now.AddDays(-1));
    return dt;
}

// Export to Excel
WorkBook reportWorkbook = WorkBook.Create();
WorkSheet reportSheet = reportWorkbook.CreateWorkSheet("Sales Report");
DataTable salesData = GetSalesData();

// Title row
reportSheet["A1"].Value = "Order Report - " + DateTime.Now.ToString("MMMM yyyy");
reportSheet.Merge("A1:F1");
reportSheet["A1"].Style.Font.Bold = true;
reportSheet["A1"].Style.Font.Height = 14;

// Headers
int headerRow = 3;
for (int col = 0; col < salesData.Columns.Count; col++)
{
    reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns[col].ColumnName);
}
var headers = reportSheet[$"A{headerRow}:F{headerRow}"];
headers.Style.Font.Bold = true;
headers.Style.SetBackgroundColor("#D9E1F2");

// Data rows
for (int row = 0; row < salesData.Rows.Count; row++)
{
    for (int col = 0; col < salesData.Columns.Count; col++)
    {
        reportSheet.SetCellValue(row + headerRow, col, salesData.Rows[row][col]);
    }
    reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}

// Total header
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency and date columns
reportSheet[$"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";

// Summary section
int summaryRow = headerRow + salesData.Rows.Count + 2;
reportSheet[$"A{summaryRow}"].Value = "Summary";
reportSheet[$"A{summaryRow}"].Style.Font.Bold = true;
reportSheet[$"A{summaryRow + 1}"].Value = "Total Orders:";
reportSheet[$"B{summaryRow + 1}"].Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})";
reportSheet[$"A{summaryRow + 2}"].Value = "Total Revenue:";
reportSheet[$"B{summaryRow + 2}"].Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})";
reportSheet[$"B{summaryRow + 2}"].FormatString = "$#,##0.00";

for (int col = 0; col <= 6; col++) { reportSheet.AutoSizeColumn(col); }
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");
using System.Data;
using IronXL;

// Simulate database retrieval (replace with actual database code)
DataTable GetSalesData()
{
    DataTable dt = new DataTable("Sales");
    dt.Columns.Add("OrderID", typeof(int));
    dt.Columns.Add("CustomerName", typeof(string));
    dt.Columns.Add("Product", typeof(string));
    dt.Columns.Add("Quantity", typeof(int));
    dt.Columns.Add("UnitPrice", typeof(decimal));
    dt.Columns.Add("OrderDate", typeof(DateTime));
    dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99m, DateTime.Now.AddDays(-5));
    dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99m, DateTime.Now.AddDays(-4));
    dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99m, DateTime.Now.AddDays(-3));
    dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99m, DateTime.Now.AddDays(-2));
    dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99m, DateTime.Now.AddDays(-1));
    return dt;
}

// Export to Excel
WorkBook reportWorkbook = WorkBook.Create();
WorkSheet reportSheet = reportWorkbook.CreateWorkSheet("Sales Report");
DataTable salesData = GetSalesData();

// Title row
reportSheet["A1"].Value = "Order Report - " + DateTime.Now.ToString("MMMM yyyy");
reportSheet.Merge("A1:F1");
reportSheet["A1"].Style.Font.Bold = true;
reportSheet["A1"].Style.Font.Height = 14;

// Headers
int headerRow = 3;
for (int col = 0; col < salesData.Columns.Count; col++)
{
    reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns[col].ColumnName);
}
var headers = reportSheet[$"A{headerRow}:F{headerRow}"];
headers.Style.Font.Bold = true;
headers.Style.SetBackgroundColor("#D9E1F2");

// Data rows
for (int row = 0; row < salesData.Rows.Count; row++)
{
    for (int col = 0; col < salesData.Columns.Count; col++)
    {
        reportSheet.SetCellValue(row + headerRow, col, salesData.Rows[row][col]);
    }
    reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}

// Total header
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency and date columns
reportSheet[$"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";

// Summary section
int summaryRow = headerRow + salesData.Rows.Count + 2;
reportSheet[$"A{summaryRow}"].Value = "Summary";
reportSheet[$"A{summaryRow}"].Style.Font.Bold = true;
reportSheet[$"A{summaryRow + 1}"].Value = "Total Orders:";
reportSheet[$"B{summaryRow + 1}"].Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})";
reportSheet[$"A{summaryRow + 2}"].Value = "Total Revenue:";
reportSheet[$"B{summaryRow + 2}"].Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})";
reportSheet[$"B{summaryRow + 2}"].FormatString = "$#,##0.00";

for (int col = 0; col <= 6; col++) { reportSheet.AutoSizeColumn(col); }
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");
Imports System.Data
Imports IronXL

' Simulate database retrieval (replace with actual database code)
Function GetSalesData() As DataTable
    Dim dt As New DataTable("Sales")
    dt.Columns.Add("OrderID", GetType(Integer))
    dt.Columns.Add("CustomerName", GetType(String))
    dt.Columns.Add("Product", GetType(String))
    dt.Columns.Add("Quantity", GetType(Integer))
    dt.Columns.Add("UnitPrice", GetType(Decimal))
    dt.Columns.Add("OrderDate", GetType(DateTime))
    dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99D, DateTime.Now.AddDays(-5))
    dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99D, DateTime.Now.AddDays(-4))
    dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99D, DateTime.Now.AddDays(-3))
    dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99D, DateTime.Now.AddDays(-2))
    dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99D, DateTime.Now.AddDays(-1))
    Return dt
End Function

' Export to Excel
Dim reportWorkbook As WorkBook = WorkBook.Create()
Dim reportSheet As WorkSheet = reportWorkbook.CreateWorkSheet("Sales Report")
Dim salesData As DataTable = GetSalesData()

' Title row
reportSheet("A1").Value = "Order Report - " & DateTime.Now.ToString("MMMM yyyy")
reportSheet.Merge("A1:F1")
reportSheet("A1").Style.Font.Bold = True
reportSheet("A1").Style.Font.Height = 14

' Headers
Dim headerRow As Integer = 3
For col As Integer = 0 To salesData.Columns.Count - 1
    reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns(col).ColumnName)
Next
Dim headers = reportSheet($"A{headerRow}:F{headerRow}")
headers.Style.Font.Bold = True
headers.Style.SetBackgroundColor("#D9E1F2")

' Data rows
For row As Integer = 0 To salesData.Rows.Count - 1
    For col As Integer = 0 To salesData.Columns.Count - 1
        reportSheet.SetCellValue(row + headerRow, col, salesData.Rows(row)(col))
    Next
    reportSheet($"G{row + headerRow + 1}").Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}"
Next

' Total header
reportSheet("G3").Value = "Total"
reportSheet("G3").Style.Font.Bold = True
reportSheet("G3").Style.SetBackgroundColor("#D9E1F2")

' Format currency and date columns
reportSheet($"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}").FormatString = "$#,##0.00"
reportSheet($"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}").FormatString = "$#,##0.00"
reportSheet($"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}").FormatString = "MM/dd/yyyy"

' Summary section
Dim summaryRow As Integer = headerRow + salesData.Rows.Count + 2
reportSheet($"A{summaryRow}").Value = "Summary"
reportSheet($"A{summaryRow}").Style.Font.Bold = True
reportSheet($"A{summaryRow + 1}").Value = "Total Orders:"
reportSheet($"B{summaryRow + 1}").Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})"
reportSheet($"A{summaryRow + 2}").Value = "Total Revenue:"
reportSheet($"B{summaryRow + 2}").Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})"
reportSheet($"B{summaryRow + 2}").FormatString = "$#,##0.00"

For col As Integer = 0 To 6
    reportSheet.AutoSizeColumn(col)
Next
reportWorkbook.EvaluateAll()
reportWorkbook.SaveAs("DatabaseExport.xlsx")
$vbLabelText   $csharpLabel

本示例演示了完整的数据库到 Excel 工作流程。 DataTable 模拟数据库检索 -- 在生产环境中,请使用 Entity Framework、Dapper 或 ADO.NET 将其替换为实际的数据库查询。 根据 Microsoft 数据导出最佳实践的建议,手动映射方法可以完全控制格式和布局。

代码会创建一个带有标题、格式化标题和数据行的专业报告。 公式列动态计算行总数。 摘要部分使用 Excel 公式来统计订单数量和汇总收入,确保如果数据发生变化,这些值也会随之更新。 要处理数据集和更大的数据结构,请参阅Excel 到数据集转换指南

输出

如何使用 IronXL 在 C# 中生成 Excel 文件:图 10 - 数据库导出到 Excel 输出

需要将Excel报表投入生产环境吗? 获取许可证,即可解锁 IronXL 在生产部署方面的全部潜力。

如何处理多个工作表?

复杂的 Excel 文件通常需要多个工作表来组织相关数据。 IronXL 通过创建、访问和组织工作表的直观方法简化了多工作表管理。 只需几行代码即可打开和管理工作簿工作表

using IronXL;
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");

// Populate Sales sheet
salesSheet["A1"].Value = "Sales Dashboard";
salesSheet["A3"].Value = "Region";
salesSheet["B3"].Value = "Q1 Sales";
salesSheet["C3"].Value = "Q2 Sales";
string[] regions = { "North", "South", "East", "West" };
decimal[] q1Sales = { 250000, 180000, 220000, 195000 };
decimal[] q2Sales = { 275000, 195000, 240000, 210000 };
for (int i = 0; i < regions.Length; i++)
{
    salesSheet[$"A{i + 4}"].Value = regions[i];
    salesSheet[$"B{i + 4}"].Value = q1Sales[i];
    salesSheet[$"C{i + 4}"].Value = q2Sales[i];
}

// Populate Inventory sheet
inventorySheet["A1"].Value = "Inventory Status";
string[] products = { "Widget A", "Widget B", "Widget C" };
int[] stock = { 150, 45, 200 };
int[] reorderPoint = { 100, 50, 75 };
for (int i = 0; i < products.Length; i++)
{
    inventorySheet[$"A{i + 4}"].Value = products[i];
    inventorySheet[$"B{i + 4}"].Value = stock[i];
    inventorySheet[$"C{i + 4}"].Value = reorderPoint[i];
    string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
    inventorySheet[$"D{i + 4}"].Value = status;
    if (status == "REORDER")
        inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}

// Summary sheet with cross-sheet formulas
summarySheet["A1"].Value = "Company Overview";
summarySheet["A4"].Value = "Total Q1 Sales";
summarySheet["B4"].Formula = "=SUM(Sales!B4:B7)";
summarySheet["A5"].Value = "Total Q2 Sales";
summarySheet["B5"].Formula = "=SUM(Sales!C4:C7)";
summarySheet["A6"].Value = "Products Need Reorder";
summarySheet["B6"].Formula = "=COUNTIF(Inventory!D4:D6,\"REORDER\")";

// Apply consistent formatting across all sheets
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
    sheet["A1"].Style.Font.Bold = true;
    sheet["A1"].Style.Font.Height = 14;
}
companyReport.SaveAs("CompanyReport.xlsx");
using IronXL;
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");

// Populate Sales sheet
salesSheet["A1"].Value = "Sales Dashboard";
salesSheet["A3"].Value = "Region";
salesSheet["B3"].Value = "Q1 Sales";
salesSheet["C3"].Value = "Q2 Sales";
string[] regions = { "North", "South", "East", "West" };
decimal[] q1Sales = { 250000, 180000, 220000, 195000 };
decimal[] q2Sales = { 275000, 195000, 240000, 210000 };
for (int i = 0; i < regions.Length; i++)
{
    salesSheet[$"A{i + 4}"].Value = regions[i];
    salesSheet[$"B{i + 4}"].Value = q1Sales[i];
    salesSheet[$"C{i + 4}"].Value = q2Sales[i];
}

// Populate Inventory sheet
inventorySheet["A1"].Value = "Inventory Status";
string[] products = { "Widget A", "Widget B", "Widget C" };
int[] stock = { 150, 45, 200 };
int[] reorderPoint = { 100, 50, 75 };
for (int i = 0; i < products.Length; i++)
{
    inventorySheet[$"A{i + 4}"].Value = products[i];
    inventorySheet[$"B{i + 4}"].Value = stock[i];
    inventorySheet[$"C{i + 4}"].Value = reorderPoint[i];
    string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
    inventorySheet[$"D{i + 4}"].Value = status;
    if (status == "REORDER")
        inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}

// Summary sheet with cross-sheet formulas
summarySheet["A1"].Value = "Company Overview";
summarySheet["A4"].Value = "Total Q1 Sales";
summarySheet["B4"].Formula = "=SUM(Sales!B4:B7)";
summarySheet["A5"].Value = "Total Q2 Sales";
summarySheet["B5"].Formula = "=SUM(Sales!C4:C7)";
summarySheet["A6"].Value = "Products Need Reorder";
summarySheet["B6"].Formula = "=COUNTIF(Inventory!D4:D6,\"REORDER\")";

// Apply consistent formatting across all sheets
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
    sheet["A1"].Style.Font.Bold = true;
    sheet["A1"].Style.Font.Height = 14;
}
companyReport.SaveAs("CompanyReport.xlsx");
Imports IronXL

Dim companyReport As WorkBook = WorkBook.Create()
' Create department sheets
Dim salesSheet As WorkSheet = companyReport.CreateWorkSheet("Sales")
Dim inventorySheet As WorkSheet = companyReport.CreateWorkSheet("Inventory")
Dim summarySheet As WorkSheet = companyReport.CreateWorkSheet("Summary")

' Populate Sales sheet
salesSheet("A1").Value = "Sales Dashboard"
salesSheet("A3").Value = "Region"
salesSheet("B3").Value = "Q1 Sales"
salesSheet("C3").Value = "Q2 Sales"
Dim regions As String() = {"North", "South", "East", "West"}
Dim q1Sales As Decimal() = {250000, 180000, 220000, 195000}
Dim q2Sales As Decimal() = {275000, 195000, 240000, 210000}
For i As Integer = 0 To regions.Length - 1
    salesSheet($"A{i + 4}").Value = regions(i)
    salesSheet($"B{i + 4}").Value = q1Sales(i)
    salesSheet($"C{i + 4}").Value = q2Sales(i)
Next

' Populate Inventory sheet
inventorySheet("A1").Value = "Inventory Status"
Dim products As String() = {"Widget A", "Widget B", "Widget C"}
Dim stock As Integer() = {150, 45, 200}
Dim reorderPoint As Integer() = {100, 50, 75}
For i As Integer = 0 To products.Length - 1
    inventorySheet($"A{i + 4}").Value = products(i)
    inventorySheet($"B{i + 4}").Value = stock(i)
    inventorySheet($"C{i + 4}").Value = reorderPoint(i)
    Dim status As String = If(stock(i) <= reorderPoint(i), "REORDER", "OK")
    inventorySheet($"D{i + 4}").Value = status
    If status = "REORDER" Then
        inventorySheet($"D{i + 4}").Style.Font.Color = "#FF0000"
    End If
Next

' Summary sheet with cross-sheet formulas
summarySheet("A1").Value = "Company Overview"
summarySheet("A4").Value = "Total Q1 Sales"
summarySheet("B4").Formula = "=SUM(Sales!B4:B7)"
summarySheet("A5").Value = "Total Q2 Sales"
summarySheet("B5").Formula = "=SUM(Sales!C4:C7)"
summarySheet("A6").Value = "Products Need Reorder"
summarySheet("B6").Formula = "=COUNTIF(Inventory!D4:D6,""REORDER"")"

' Apply consistent formatting across all sheets
For Each sheet As WorkSheet In companyReport.WorkSheets
    sheet("A1").Style.Font.Bold = True
    sheet("A1").Style.Font.Height = 14
Next

companyReport.SaveAs("CompanyReport.xlsx")
$vbLabelText   $csharpLabel

本示例创建了一份完整的多页报告。 每个工作表都有其特定用途:销售数据、库存跟踪和汇总视图。 汇总表使用跨表公式合并关键指标。 请注意工作表引用语法——"Sales!B4:B7"指的是销售工作表中的单元格 B4 到 B7。

库存表展示了条件逻辑,将低库存商品染成红色,以便立即引起注意。 foreach 循环在所有工作表中应用一致的格式,从而在整个工作簿中保持专业的外观。 工作表名称在 Excel 中以标签页的形式显示,使用户能够轻松地在不同的数据视图之间切换。

C#中生成Excel文件的最佳实践是什么?

在 C# 中高效生成 Excel 文件需要在内存使用、错误处理和部署方面考虑周到。 在以编程方式创建 Excel 电子表格时,这些实践可确保您的应用程序有效扩展,同时保持可靠性。

对于大文件,内存管理变得至关重要。 分批处理数据,而不是一次性加载整个数据集。 以下模式可确保高容量导出操作的内存使用量可预测:

using IronXL;
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Value";
// Process records in manageable batches
foreach (var batch in GetDataInBatches(rowsPerBatch))
{
    foreach (var record in batch)
    {
        sheet[$"A{currentRow}"].Value = record.Id;
        sheet[$"B{currentRow}"].Value = record.Name;
        sheet[$"C{currentRow}"].Value = record.Value;
        currentRow++;
    }
}
workbook.SaveAs("LargeDataset.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Value";
// Process records in manageable batches
foreach (var batch in GetDataInBatches(rowsPerBatch))
{
    foreach (var record in batch)
    {
        sheet[$"A{currentRow}"].Value = record.Id;
        sheet[$"B{currentRow}"].Value = record.Name;
        sheet[$"C{currentRow}"].Value = record.Value;
        currentRow++;
    }
}
workbook.SaveAs("LargeDataset.xlsx");
Imports IronXL

Dim workbook As WorkBook = WorkBook.Create()
Dim sheet As WorkSheet = workbook.CreateWorkSheet("Data")
Dim rowsPerBatch As Integer = 1000
Dim currentRow As Integer = 2
sheet("A1").Value = "ID"
sheet("B1").Value = "Name"
sheet("C1").Value = "Value"
' Process records in manageable batches
For Each batch In GetDataInBatches(rowsPerBatch)
    For Each record In batch
        sheet($"A{currentRow}").Value = record.Id
        sheet($"B{currentRow}").Value = record.Name
        sheet($"C{currentRow}").Value = record.Value
        currentRow += 1
    Next
Next
workbook.SaveAs("LargeDataset.xlsx")
$vbLabelText   $csharpLabel

对于 Web 应用程序,在内存中生成 Excel 文件并直接流式传输给用户,而不是将临时文件写入磁盘。 始终将生成逻辑封装在错误处理程序中,以防止崩溃并提供有意义的反馈:

// ASP.NET Core controller action with error handling
IActionResult DownloadExcel()
{
    try
    {
        WorkBook workbook = WorkBook.Create();
        WorkSheet sheet = workbook.CreateWorkSheet("Report");
        sheet["A1"].Value = "Report Data";
        // Populate report data here...
        var stream = new MemoryStream();
        workbook.SaveAs(stream);
        stream.Position = 0;
        return File(stream,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "report.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Excel generation failed: {ex.Message}");
        return StatusCode(500, "Failed to generate Excel file.");
    }
}
// ASP.NET Core controller action with error handling
IActionResult DownloadExcel()
{
    try
    {
        WorkBook workbook = WorkBook.Create();
        WorkSheet sheet = workbook.CreateWorkSheet("Report");
        sheet["A1"].Value = "Report Data";
        // Populate report data here...
        var stream = new MemoryStream();
        workbook.SaveAs(stream);
        stream.Position = 0;
        return File(stream,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "report.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Excel generation failed: {ex.Message}");
        return StatusCode(500, "Failed to generate Excel file.");
    }
}
Imports System
Imports System.IO
Imports Microsoft.AspNetCore.Mvc

Public Class YourController
    Inherits Controller

    Public Function DownloadExcel() As IActionResult
        Try
            Dim workbook As WorkBook = WorkBook.Create()
            Dim sheet As WorkSheet = workbook.CreateWorkSheet("Report")
            sheet("A1").Value = "Report Data"
            ' Populate report data here...
            Dim stream As New MemoryStream()
            workbook.SaveAs(stream)
            stream.Position = 0
            Return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx")
        Catch ex As Exception
            Console.WriteLine($"Excel generation failed: {ex.Message}")
            Return StatusCode(500, "Failed to generate Excel file.")
        End Try
    End Function
End Class
$vbLabelText   $csharpLabel

下表总结了关键最佳实践及其适用场景:

IronXL在 C# 中生成 Excel 的最佳实践
场景 建议的翻译方法 益处
Large datasets (>10,000 rows) 使用分块写入进行批量处理 减少内存占用
网页应用程序下载 使用 MemoryStream 而不是临时文件 无磁盘 I/O,响应速度更快
生产部署 请提供有效的IronXL许可证密钥 生成的文件上没有水印
货币和日期 使用 FormatString 属性 Excel 中正确的区域设置显示
动态报表 在 SaveAs() 之前调用 EvaluateAll() 公式显示计算值

IronXL 可在受限环境中工作,无需提升权限,因此适合共享主机和容器化部署。 将IronXL许可证文件包含在部署包中,并确保应用程序具有对任何所需临时文件操作的写入权限。 有关更多部署指导,请参阅IronXL功能概述和完整的API 文档

接下来你能去哪里?

IronXL 将 Excel 文件在 C# 中的生成从一个复杂的挑战转变为简单明了的编码。 您已经学会了创建工作簿、填充单元格、应用格式、使用公式、导出数据库数据以及管理多个工作表——所有这些都不需要依赖 Microsoft Office。 这些技术在面向.NET 10 的 Windows、Linux 和云平台上都能稳定运行。

要深入了解,请浏览IronXL 的操作指南,了解如何读取和修改现有的 Excel 文件,或者访问试用许可证页面,开始在生产环境中使用。 查看符合您项目需求和规模的许可选项

如何使用 IronXL 在 C# 中生成 Excel 文件:图 11 - 许可

常见问题解答

如何使用C#生成Excel文件?

您可以使用IronXL在 C# 中生成 Excel 文件,它提供了一个简单的 API 来创建 Excel 文件,而无需安装 Microsoft Office 或复杂的 COM 互操作。

在C#中处理Excel文件是否需要微软Office?

不,无需安装 Microsoft Office。IronXL 允许您使用 C# 创建和操作 Excel 文件,而无需依赖任何 Office 套件。

使用IronXL相对于传统方法有哪些优势?

IronXL简化了生成 Excel 文件的过程,无需 Microsoft Office 和复杂的 COM 互操作,提供了用于创建和操作 Excel 文件的简单 API。

我可以使用IronXL将数据库与 Excel 文件集成吗?

是的, IronXL支持数据库集成等高级操作,可让您高效地将数据导出到 Excel 文件。

IronXL可以生成哪些文件格式?

IronXL允许您创建 XLS 和 XLSX 文件格式,使其能够灵活满足不同的 Excel 文件生成需求。

IronXL是否支持 Excel 文件中的高级格式设置?

是的, IronXL支持高级格式设置功能,使您能够自定义 Excel 文件的外观和结构。

是否可以使用IronXL自动生成电子表格?

是的, IronXL提供工具和技术来自动生成电子表格,简化报告创建和数据导出等流程。

如何在.NET应用程序中使用Excel创建报表?

IronXL提供了一种简单的方法来创建报告,它可以直接在.NET应用程序中生成 Excel 文件,为数据呈现提供强大的解决方案。

使用 C# 处理 Excel 时,有哪些必备技巧?

使用IronXL在 C# 中处理 Excel 的基本技巧包括创建基本电子表格、高级格式设置和数据库集成。

哪里可以找到有关在 C# 中使用IronXL 的文档?

您可以在Iron Software网站上找到有关在 C# 中使用IronXL的全面文档,其中包括各种用例的教程和示例。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

钢铁支援团队

我们每周 5 天,每天 24 小时在线。
聊天
电子邮件
打电话给我