如何在C#中创建Excel文件

How to Create an Excel File in C# (.NET Tutorial)

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

IronXL是一个功能强大的 C# 和 .NET Excel 库,它允许您以编程方式创建、读取和编辑 XLSX 电子表格,而无需 Microsoft Office或 Interop 依赖项。 它支持 .NET 8、.NET 9、.NET Core、.NET Framework,并可在 Windows、Linux、macOS、Azure 和 AWS 上运行。

本教程将引导您使用 C# 构建完整的 Excel 工作簿:设置单元格值、应用格式、添加公式以及导出为 XLSX、CSV 等格式——并提供分步代码示例。

快速入门:创建 Excel 文件

使用 IronXL 可以立即创建一个新的 Excel 文件——只需选择格式、添加工作表、设置任意单元格值并保存即可。 这是生成 XLSX 文件的最快方法,它具有直观的 API 调用,并且不会出现任何互操作性问题。

  1. 使用 NuGet 包管理器安装 https://www.nuget.org/packages/IronXl.Excel

    PM > Install-Package IronXl.Excel
  2. 复制并运行这段代码。

    WorkBook book = IronXl.WorkBook.Create(IronXl.ExcelFileFormat.XLSX); book.CreateWorkSheet("Sheet1")["A1"].Value = "Hello World"; book.SaveAs("MyFile.xlsx");
  3. 部署到您的生产环境中进行测试

    通过免费试用立即在您的项目中开始使用IronXL

    arrow pointer

什么是 IronXL?为什么要使用它来创建 Excel 文件?

IronXL 是一个直观的 C# 和 VB Excel API ,使您能够在 .NET 中读取、编辑和创建 Excel 电子表格文件,并具有卓越的性能。 与传统方法不同,无需安装 Microsoft Office 或使用 Excel Interop,使部署更简单、更可靠。

IronXL 完全支持 .NET 9、.NET 8、.NET Core、.NET Framework、Xamarin、移动、Linux、macOS 和 Azure 环境。

IronXL 功能

  • 由我们的 .NET 开发团队直接提供人工支持 使用 Microsoft Visual Studio 快速安装
  • 免费用于开发。 许可证来自 $799

如何快速创建并保存Excel文件?

通过 NuGet 安装 IronXL直接下载 DLL 文件WorkBook 类是您进行所有 Excel 操作的入口点,而 WorkSheet 类提供了操作单个工作表的方法——完整的逐步演练从下面的步骤 1 开始。


How Do I Install the IronXL C# Library?

在 Visual Studio 中通过 NuGet 包管理器安装 IronXL,或者使用包管理器控制台:

Install-Package IronXl.Excel

通过"项目"菜单或在"解决方案资源管理器"中右键单击项目来访问 NuGet 包管理器。

Visual Studio 项目菜单中显示

**图 3** –*通过"项目"菜单访问 NuGet 包管理器*

解决方案资源管理器上下文菜单显示

**图 4** –*解决方案资源管理器中的右键单击上下文菜单*


在软件包列表中浏览 IronXl.Excel,然后单击"安装"。


NuGet 包管理器显示 IronXl.Excel 包已准备好安装

**图 5** –*通过 NuGet 包管理器安装 IronXl.Excel*

或者,直接下载IronXL DLL ,然后通过"解决方案资源管理器">"引用">"浏览"将其作为引用添加到您的项目中。

IronXL 网站下载页面显示了安装说明和下载按钮

**图 6** –*从官方网站下载 IronXL 库*

IronXL 无需安装 Microsoft Office 或 Excel Interop,可在任何支持 .NET 的平台上运行,包括 Windows、Linux、macOS 和云环境。


如何设置我的.NET项目?

IronXL 适用于任何.NET 项目类型——控制台应用程序、ASP.NET Web 应用程序、API 或桌面工具。 下面的示例使用 ASP.NET Web 应用程序,但所有项目模板的处理过程都相同。

按照以下步骤创建 ASP.NET 网站:

  1. 打开Visual Studio 2.单击文件 > 新项目
  2. 在"项目类型"列表中,选择"Visual C#"下的"Web"。
  3. 选择 ASP.NET Web 应用程序


    Visual Studio 新建项目对话框,并选中 ASP.NET Web 应用程序

    图 1 – Create new ASP.NET project

  4. 单击"确定"
  5. 选择 Web 表单模板

    ASP.NET 项目模板选择,显示 Web 窗体选项

    图 2 – Select Web Forms template

  6. 单击"确定"

项目准备就绪后,安装 IronXL 即可开始以编程方式创建 Excel 文件。


How Do I Create an Excel Workbook in C#?

使用 IronXL 创建新的 Excel 工作簿只需要一行代码:

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);
$vbLabelText   $csharpLabel

WorkBook.Create 方法同时支持 XLS(Excel 97-2003)和 XLSX(Excel 2007+)格式。 建议使用 XLSX 格式以获得更好的性能和更小的文件大小。

  • XLSX :推荐用于所有现代 Excel 版本(2007 及更高版本)——文件更小,性能更佳
  • XLS :与 Excel 97–2003 兼容的旧格式

如何向我的工作簿中添加工作表?

添加工作表很简单:

// 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");
$vbLabelText   $csharpLabel

一本练习册包含一张或多张练习题。 每个工作表都由行和列组成,单元格位于行和列的交叉点。 使用CreateWorkSheet 方法向工作簿添加新工作表。

  • CreateWorkSheet("name") :添加一个具有指定选项卡名称的新工作表
  • GetWorkSheet("name") :按名称检索现有工作表 工作簿中的工作表名称必须唯一。

如何在Excel中设置单元格值?

如何手动设置单元格值?

设置单个单元格值时,可以使用类似 Excel 的直观语法:

// 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
$vbLabelText   $csharpLabel

Cell.Value 属性接受各种数据类型,包括字符串、数字、日期和布尔值。 IronXL会根据数据类型自动格式化单元格。

如何动态设置单元格值?

动态值设置非常适合数据驱动型应用:

// 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
$vbLabelText   $csharpLabel

字符串插值($"A{i}")使动态引用单元格变得容易。 Range 索引器支持单个单元格和范围。

如何从数据库中导入数据到Excel?

将数据库中的数据导入Excel是一项常见需求:

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})";
$vbLabelText   $csharpLabel

本示例演示如何从数据库读取 Excel 数据、应用格式以及使用公式进行计算。 FormatString 属性可以像在 Excel 中一样自定义数字格式。


如何对Excel单元格应用格式?

如何在Excel中设置背景颜色?

单元格样式可以增强可读性和视觉吸引力:

// 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");
    }
}
$vbLabelText   $csharpLabel

Style.SetBackgroundColor 方法接受十六进制颜色代码。 将背景颜色与字体颜色结合使用,打造专业美观的电子表格。

如何在Excel中创建边框?

边界有助于定义数据区域并改善数据结构:

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
$vbLabelText   $csharpLabel

IronXL 支持多种边框类型,包括细边框、中等边框、粗边框、双边框、点状边框和虚线边框。 边框的每一边都可以独立设置样式。


How Do I Use Excel Formulas in C#?

IronXL 提供强大的公式支持和自动计算功能:

// 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();
$vbLabelText   $csharpLabel

Range提供了诸如 Max()Min() 之类的方法,用于快速计算。 对于更复杂的场景,可以使用Formula 属性直接设置 Excel 公式。

处理范围时,建议优先使用 IronXL 内置的 .Max().Min() 方法,而不是原始公式字符串——它们类型安全,并且避免公式语法错误。


如何设置工作表和打印属性?

使用 IronXL 保护单个工作表、冻结行和列,以及设置打印格式选项。

如何配置工作表属性?

保护工作表并控制查看选项:

// 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

工作表保护功能可防止意外修改,而冻结窗格功能可在滚动时保持重要行或列可见。

Excel 表格显示了包含月度预算数据的冻结标题行

**图 7** –*冻结的标题行在滚动时仍然可见*

Excel 保护对话框要求输入密码才能修改受保护的工作表

**图 8** –*密码保护防止未经授权的编辑*

如何配置页面和打印设置?

通过 IronXL 设置专业打印选项:

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
$vbLabelText   $csharpLabel

PrintSetup提供与 Excel 打印设置相匹配的全面打印配置选项。

Excel 打印预览显示横向打印方向和 A4 纸张尺寸设置

**图 9** –*横向打印预览及自定义边距*


如何保存我的Excel工作簿?

将工作簿保存为多种格式:

// 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);
$vbLabelText   $csharpLabel

IronXL 支持多种导出格式,包括 XLSX、XLS、CSV、TSV 和 JSON。 SaveAs 方法会自动根据文件扩展名确定格式。

  • XLSX / XLS :完整的 Excel 格式,包含格式、公式和多个工作表
  • CSV :纯文本格式,用于数据交换——每个文件导出一个工作表 JSON :用于 Web API 和数据管道的结构化输出 -:用于内存输出——适用于网页下载或云存储

摘要

本教程演示了如何使用IronXL在 C# 中创建不依赖 Microsoft Office 的 Excel 文件。 您学习了Excel的基本操作,包括创建工作簿、单元格操作、格式设置、公式使用以及各种保存选项。 IronXL 直观的 API 使 .NET 开发人员能够轻松实现Excel 自动化

如需了解更多高级功能,请探索合并单元格创建图表。 准备好在生产中使用 IronXL 了吗? 开始免费试用查看许可选项

下一步是什么?

既然您现在可以用 C# 创建 Excel 文件,不妨探索一下 IronXL 的这些相关功能:

-读取和编辑现有 Excel 文件 -在 Excel 中合并单元格 -使用 C# 创建 Excel 图表 -电子表格格式之间的转换 IronXL API 参考


教程快速访问

Visual Studio 徽标
### 下载本教程的 C# 源代码

用于创建 Excel 文件的完整 C# 源代码以 Visual Studio 项目文件的形式提供。

下载
### 在 GitHub 上探索此教程

该项目的源代码可在 GitHub 上找到,提供 C# 和 VB.NET 两种版本。

使用此代码,您可以在几分钟内轻松创建 Excel 文件。该项目保存为 Microsoft Visual Studio 项目,但与任何 .NET IDE 都兼容。

在 GitHub 上使用 C# 创建 Excel 文件
GitHub 标志
API 文档图标
### 请阅读 IronXL API 参考文档

探索 IronXL 的 API 参考,其中详细介绍了所有功能、命名空间、类、方法和属性,以便在 .NET 中进行全面的 Excel 操作。

查看 API 参考

常见问题解答

如何在 C# 中不使用 Interop 创建 Excel 文件?

您可以通过使用 IronXL 创建不使用 Interop 的 Excel 文件,这提供了一个简单的 API:WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX)。此方法在任何 .NET 平台上都适用,无需安装 Microsoft Office。

C# 支持哪些平台进行 Excel 文件创建?

IronXL支持在.NET 10、.NET 9、.NET 8、.NET Core、.NET Framework 4.6.2+上创建Excel文件,运行在Windows、macOS、Linux、Docker、Azure和AWS环境中。

如何为 Excel 生成安装 C# 库?

通过 Visual Studio 中的 NuGet 包管理器安装 IronXL,使用命令PM> Install-Package IronXl.Excel,或直接从 nuget.org 下载。

如何以编程方式创建新的 Excel 工作簿?

使用 IronXL 创建工作簿:WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX),然后使用workbook.CreateWorkSheet("SheetName")添加工作表。

如何使用 C# 在 Excel 工作表中设置单元格值?

使用 IronXL 的直观语法设置单元格值:worksheet["A1"].Value = "Hello World"或设置范围:worksheet["A1:A10"].Value = 100

可以以编程方式为 Excel 单元格应用格式吗?

可以,IronXL 支持综合格式设置,包括背景颜色(cell.Style.SetBackgroundColor("#FF0000")),边框,字体和数字格式。

如何在 C# 中使用 Excel 公式?

使用 IronXL 的 Formula 属性应用公式:worksheet["A1"].Formula = "=SUM(B1:B10)",或使用内置方法如range.Sum()range.Avg()

我如何用密码保护 Excel 工作表?

使用 worksheet.ProtectSheet("YourPassword") 在 IronXL 中保护工作表,以防止未经授权的修改。

如何配置 Excel 文件的打印设置?

使用 IronXL 的 PrintSetup 设置打印属性:worksheet.PrintSetup.PrintOrientation = PrintOrientation.Landscapeworksheet.SetPrintArea("A1:Z100")

如何以不同格式保存 Excel 工作簿?

使用 IronXL 的 SaveAs 方法保存工作簿:workbook.SaveAs("file.xlsx")用于 XLSX,或使用SaveAsCsv()SaveAsJson()用于其他格式。

如何用数据库数据填充 Excel 表?

使用 IronXL 填充工作表,通过从数据库获取数据并使用worksheet["A1"].Value = dataFromDatabase方法设置在单元格中。

如何在 C# 中在 Excel 表中实现冻结窗格功能?

通过 IronXL 使用worksheet.FreezePanes(1, 1)冻结窗格,以锁定顶行和最左列,方便导航。

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

Jacob 拥有曼彻斯特大学土木工程一级荣誉工程学士学位(BEng)(1998-2001 年)。他的旗舰产品 IronPDF 和 Iron Suite for .NET 库在全球的 NuGet 安装量已超过 3000 万次,其基础代码继续为全球使用的开发人员工具提供动力。Jacob 拥有 25 年的商业经验和 41 年的编码专业知识,他一直专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/ready_to_started_202509.php
Line: 12
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 489
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/ready_to_started_202509.php
Line: 19
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 489
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

准备开始了吗?
Nuget 下载 1,890,100 | 版本: 2026.3 刚刚发布

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/still_scrolling_202512.php
Line: 17
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 71
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/still_scrolling_202512.php
Line: 24
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 71
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package IronXl.Excel
运行示例 观看您的数据变成电子表格。