C# 创建 Excel 文件教程

Jonas是一家位于慕尼黑的.NET软件公司的首席开发人员。Jonas使用IronXL来推动客户的会计和销售管道Excel文档之间的数据交换。IronXL正在成为Jonas许多客户会计系统项目中的常用工具。
乔纳斯·施密特
2019年五月26日
更新 2024年十二月10日
分享:
This article was translated from English: Does it need improvement?
Translated
View the article in English

本教程将逐步指导您如何在支持 .NET Framework 4.5 或 .NET Core 的任何平台上创建 Excel 工作簿文件。 在 C# 中创建 Excel 文件可以很简单,甚至无需依赖传统的 Microsoft.Office.Interop.Excel 库。 使用IronXL设置工作表属性,如冻结窗格和保护,设置打印属性等。


概述

IronXL Creates C# Excel Files in .NET

IronXL 是一个直观的 C# 和 VB Excel API,使您能够在 .NET 中以极快的速度读取、编辑和创建 Excel 电子表格文件。 无需安装 MS Office 或 Excel Interop。

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

IronXL 功能:

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

    创建并保存 Excel 文件:快速代码

    https://www.nuget.org/packages/IronXL.Excel/ 作为替代方案,可以下载IronXL.dll并添加到您的项目中。

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-1.cs
using IronXL;

// Default file format is XLSX, we can override it using CreatingOptions
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
var workSheet = workBook.CreateWorkSheet("example_sheet");
workSheet["A1"].Value = "Example";

// Set value to multiple cells
workSheet["A2:A4"].Value = 5;
workSheet["A5"].Style.SetBackgroundColor("#f0f0f0");

// Set style to multiple cells
workSheet["A5:A6"].Style.Font.Bold = true;

// Set formula
workSheet["A6"].Value = "=SUM(A2:A4)";
if (workSheet["A6"].IntValue == workSheet["A2:A4"].IntValue)
{
    Console.WriteLine("Basic test passed");
}
workBook.SaveAs("example_workbook.xlsx");
Imports IronXL

' Default file format is XLSX, we can override it using CreatingOptions
Private workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Private workSheet = workBook.CreateWorkSheet("example_sheet")
Private workSheet("A1").Value = "Example"

' Set value to multiple cells
Private workSheet("A2:A4").Value = 5
workSheet("A5").Style.SetBackgroundColor("#f0f0f0")

' Set style to multiple cells
workSheet("A5:A6").Style.Font.Bold = True

' Set formula
workSheet("A6").Value = "=SUM(A2:A4)"
If workSheet("A6").IntValue = workSheet("A2:A4").IntValue Then
	Console.WriteLine("Basic test passed")
End If
workBook.SaveAs("example_workbook.xlsx")
$vbLabelText   $csharpLabel

步骤 1

1. 下载免费的 IronXL C# 库

立即在您的项目中开始使用IronXL,并享受免费试用。

第一步:
green arrow pointer


使用 NuGet 安装

有三种不同的方法来安装IronXL NuGet包:

  1. Visual Studio

  2. 开发人员命令提示符

  3. 直接下载 NuGet 软件包

    Visual Studio

    Visual Studio为您提供了NuGet包管理器,您可以使用它在项目中安装NuGet包。 您可以通过项目菜单或右键单击解决方案资源管理器中的项目来访问它。 这两个选项如图3和图4所示。

    Project Menu related to Visual Studio

    图 3项目菜单

    Right Click Solution Explorer related to Visual Studio

    Figure 4Right click Solution Explorer


    单击任一选项中的 "管理 NuGet 软件包 "后,浏览 IronXL.Excel 软件包并安装,如图 5 所示。

    Install Iron Excel Nuget Package related to Visual Studio

    Figure 5Install IronXL.Excel NuGet Package

    开发人员命令提示符

    打开开发者命令提示符并按照以下步骤安装 IronXL.Excel NuGet 软件包:

  4. 搜索您的开发者命令提示符 - 它通常位于您的Visual Studio文件夹下。

  5. 输入以下命令:

  6. PM > Install-Package IronXL.Excel

  7. 按回车键

  8. 该软件包将被安装。

  9. 重新加载 Visual Studio 项目

    直接下载 NuGet 软件包

    为了下载NuGet包,请使用以下几个步骤:

  10. 导航到以下网址:https://www.nuget.org/packages/ironxl.excel/

  11. 点击下载软件包

  12. 下载软件包后,双击

  13. 重新加载 Visual Studio 项目

    通过直接下载程序库安装 IronXL

    安装 IronXL 的第二种方法是直接从以下网址下载:https://ironsoftware.com/csharp/excel/

    Download Ironxl Library related to 通过直接下载程序库安装 IronXL

    Figure 6Download IronXL library

    通过以下步骤在项目中引用库:

  14. 在解决方案资源管理器中右击解决方案。

  15. 选择参考资料

  16. 浏览 IronXL.dll 库

  17. 点击确定

    我们走

    现在您已设置好,我们可以开始使用IronXL库中的强大功能了!

    教程

2. 创建一个 ASP.NET 项目 ##

遵循以下步骤来创建一个ASP.NET网站

  1. 打开 Visual Studio

  2. 单击文件 > 新项目

  3. 在项目类型列表框中选择 Visual C# 下的 Web

  4. 选择 ASP.NET Web 应用程序,如下所示

    New Project Asp Net related to 2. 创建一个 ASP.NET 项目 ##

    图 1新项目

  5. 点击确定

  6. 在下一个屏幕中,选择 Web 表单,如图 2 下方所示

    Web Form related to 2. 创建一个 ASP.NET 项目 ##

    图2Web窗体

  7. 点击确定

    现在我们有办法了。 安装 IronXL 以开始自定义您的文件。


3. 创建一个 Excel 工作簿

使用IronXL创建新的Excel工作簿再简单不过了! 这是一行代码! 是的,真的:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-2.cs
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
$vbLabelText   $csharpLabel

使用IronXL可以创建XLS(旧版Excel文件)和XLSX(当前和新版文件)文件格式。

3.1. 设置默认工作表 ###

而且,创建一个默认工作表更加简单:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-3.cs
WorkSheet workSheet = workBook.CreateWorkSheet("2020 Budget");
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("2020 Budget")
$vbLabelText   $csharpLabel

在上面的代码片段中,“Sheet”代表工作表,您可以使用它来设置单元格值以及几乎所有Excel能做的事情。

如果您对工作簿和工作表之间的区别感到困惑,让我来解释一下:

工作簿包含工作表。 这意味着您可以在一个工作簿中添加任意多的工作表。 在后面的文章中,我将解释如何做到这一点。 工作表包含行和列。 行和列的交点称为单元格,这是您在使用Excel时将要操作的对象。


4. 设置单元格值

4.1. 手动设置单元格值 ###

要手动设置单元格值,只需指明您正在操作的单元格,并设置其值,如下例所示:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-4.cs
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";
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"
$vbLabelText   $csharpLabel

在这里,我填充了 A 列至 L 列,每列的第一行都填充了不同月份的名称。

4.2. 动态设置单元格值 ###

设置动态值与前一个代码段几乎相似。 这个的好处是你不需要硬编码单元格位置。 在下一个代码示例中,您将创建一个新的 Random 对象来生成随机数,然后使用 for 循环遍历您想要填充值的单元格范围。

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-5.cs
Random r = new Random();
for (int i = 2 ; i <= 11 ; i++)
{
    workSheet["A" + i].Value = r.Next(1, 1000);
    workSheet["B" + i].Value = r.Next(1000, 2000);
    workSheet["C" + i].Value = r.Next(2000, 3000);
    workSheet["D" + i].Value = r.Next(3000, 4000);
    workSheet["E" + i].Value = r.Next(4000, 5000);
    workSheet["F" + i].Value = r.Next(5000, 6000);
    workSheet["G" + i].Value = r.Next(6000, 7000);
    workSheet["H" + i].Value = r.Next(7000, 8000);
    workSheet["I" + i].Value = r.Next(8000, 9000);
    workSheet["J" + i].Value = r.Next(9000, 10000);
    workSheet["K" + i].Value = r.Next(10000, 11000);
    workSheet["L" + i].Value = r.Next(11000, 12000);
}
Dim r As New Random()
For i As Integer = 2 To 11
	workSheet("A" & i).Value = r.Next(1, 1000)
	workSheet("B" & i).Value = r.Next(1000, 2000)
	workSheet("C" & i).Value = r.Next(2000, 3000)
	workSheet("D" & i).Value = r.Next(3000, 4000)
	workSheet("E" & i).Value = r.Next(4000, 5000)
	workSheet("F" & i).Value = r.Next(5000, 6000)
	workSheet("G" & i).Value = r.Next(6000, 7000)
	workSheet("H" & i).Value = r.Next(7000, 8000)
	workSheet("I" & i).Value = r.Next(8000, 9000)
	workSheet("J" & i).Value = r.Next(9000, 10000)
	workSheet("K" & i).Value = r.Next(10000, 11000)
	workSheet("L" & i).Value = r.Next(11000, 12000)
Next i
$vbLabelText   $csharpLabel

从A2到L11的每个单元格都包含一个随机生成的唯一值。

讨论动态值,何不学习如何从数据库直接动态地向单元格中添加数据? 下面的代码片段快速展示了如何操作,前提是您已正确设置了数据库连接。

4.3. 直接从数据库中添加 ###

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-6.cs
// Create database objects to populate data from database
string contring;
string sql;
DataSet ds = new DataSet("DataSetName");
SqlConnection con;
SqlDataAdapter da;

// Set Database Connection string
contring = @"Data Source=Server_Name;Initial Catalog=Database_Name;User ID=User_ID;Password=Password";

// SQL Query to obtain data
sql = "SELECT Field_Names FROM Table_Name";

// Open Connection & Fill DataSet
con = new SqlConnection(contring);
da = new SqlDataAdapter(sql, con);
con.Open();
da.Fill(ds);

// Loop through contents of dataset
foreach (DataTable table in ds.Tables)
{
    int Count = table.Rows.Count - 1;
    for (int j = 12; j <= 21; j++)
    {
        workSheet["A" + j].Value = table.Rows[Count]["Field_Name_1"].ToString();
        workSheet["B" + j].Value = table.Rows[Count]["Field_Name_2"].ToString();
        workSheet["C" + j].Value = table.Rows[Count]["Field_Name_3"].ToString();
        workSheet["D" + j].Value = table.Rows[Count]["Field_Name_4"].ToString();
        workSheet["E" + j].Value = table.Rows[Count]["Field_Name_5"].ToString();
        workSheet["F" + j].Value = table.Rows[Count]["Field_Name_6"].ToString();
        workSheet["G" + j].Value = table.Rows[Count]["Field_Name_7"].ToString();
        workSheet["H" + j].Value = table.Rows[Count]["Field_Name_8"].ToString();
        workSheet["I" + j].Value = table.Rows[Count]["Field_Name_9"].ToString();
        workSheet["J" + j].Value = table.Rows[Count]["Field_Name_10"].ToString();
        workSheet["K" + j].Value = table.Rows[Count]["Field_Name_11"].ToString();
        workSheet["L" + j].Value = table.Rows[Count]["Field_Name_12"].ToString();
    }
    Count++;
}
' Create database objects to populate data from database
Dim contring As String
Dim sql As String
Dim ds As New DataSet("DataSetName")
Dim con As SqlConnection
Dim da As SqlDataAdapter

' Set Database Connection string
contring = "Data Source=Server_Name;Initial Catalog=Database_Name;User ID=User_ID;Password=Password"

' SQL Query to obtain data
sql = "SELECT Field_Names FROM Table_Name"

' Open Connection & Fill DataSet
con = New SqlConnection(contring)
da = New SqlDataAdapter(sql, con)
con.Open()
da.Fill(ds)

' Loop through contents of dataset
For Each table As DataTable In ds.Tables
	Dim Count As Integer = table.Rows.Count - 1
	For j As Integer = 12 To 21
		workSheet("A" & j).Value = table.Rows(Count)("Field_Name_1").ToString()
		workSheet("B" & j).Value = table.Rows(Count)("Field_Name_2").ToString()
		workSheet("C" & j).Value = table.Rows(Count)("Field_Name_3").ToString()
		workSheet("D" & j).Value = table.Rows(Count)("Field_Name_4").ToString()
		workSheet("E" & j).Value = table.Rows(Count)("Field_Name_5").ToString()
		workSheet("F" & j).Value = table.Rows(Count)("Field_Name_6").ToString()
		workSheet("G" & j).Value = table.Rows(Count)("Field_Name_7").ToString()
		workSheet("H" & j).Value = table.Rows(Count)("Field_Name_8").ToString()
		workSheet("I" & j).Value = table.Rows(Count)("Field_Name_9").ToString()
		workSheet("J" & j).Value = table.Rows(Count)("Field_Name_10").ToString()
		workSheet("K" & j).Value = table.Rows(Count)("Field_Name_11").ToString()
		workSheet("L" & j).Value = table.Rows(Count)("Field_Name_12").ToString()
	Next j
	Count += 1
Next table
$vbLabelText   $csharpLabel

您只需将特定单元格的 Value 属性设置为要输入该单元格的字段名。


5. 应用格式 ##

5.1. 设置单元格背景颜色

要设置单元格或一系列单元格的背景颜色,您只需一行代码,如下所示:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-7.cs
workSheet["A1:L1"].Style.SetBackgroundColor("#d3d3d3");
workSheet("A1:L1").Style.SetBackgroundColor("#d3d3d3")
$vbLabelText   $csharpLabel

这将单元格范围的背景颜色设置为灰色。 颜色采用RGB(红色、绿色、蓝色)格式,其中前两个字符代表红色,接下来的两个字符代表绿色,最后两个字符代表蓝色。 取值范围从 0 到 9,然后是 A 到 F(十六进制)。

5.2. 创建边框

使用IronXL创建边框非常简单,如下所示:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-8.cs
workSheet["A1:L1"].Style.TopBorder.SetColor("#000000");
workSheet["A1:L1"].Style.BottomBorder.SetColor("#000000");
workSheet["L2:L11"].Style.RightBorder.SetColor("#000000");
workSheet["L2:L11"].Style.RightBorder.Type = IronXL.Styles.BorderType.Medium;
workSheet["A11:L11"].Style.BottomBorder.SetColor("#000000");
workSheet["A11:L11"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Medium;
workSheet("A1:L1").Style.TopBorder.SetColor("#000000")
workSheet("A1:L1").Style.BottomBorder.SetColor("#000000")
workSheet("L2:L11").Style.RightBorder.SetColor("#000000")
workSheet("L2:L11").Style.RightBorder.Type = IronXL.Styles.BorderType.Medium
workSheet("A11:L11").Style.BottomBorder.SetColor("#000000")
workSheet("A11:L11").Style.BottomBorder.Type = IronXL.Styles.BorderType.Medium
$vbLabelText   $csharpLabel

在上面的代码中,我为单元格A1到L1设置了黑色的顶部和底部边框,然后为单元格L2到L11设置了右边框,边框的样式设置为中等。 最后,我为A11到L11单元格设置了底部边框。


6. 在单元格中使用公式

我一直在说IronXL让一切变得如此简单,但这确实如此,我无法强调得足够多! 以下代码允许您使用公式:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-9.cs
// Use IronXL built-in aggregations
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 value to cells
workSheet["A12"].Value = sum;
workSheet["B12"].Value = avg;
workSheet["C12"].Value = max;
workSheet["D12"].Value = min;
' Use IronXL built-in aggregations
Dim sum As Decimal = workSheet("A2:A11").Sum()
Dim avg As Decimal = workSheet("B2:B11").Avg()
Dim max As Decimal = workSheet("C2:C11").Max()
Dim min As Decimal = workSheet("D2:D11").Min()

' Assign value to cells
workSheet("A12").Value = sum
workSheet("B12").Value = avg
workSheet("C12").Value = max
workSheet("D12").Value = min
$vbLabelText   $csharpLabel

关于这一点很好的是,您可以设置单元格的数据类型,从而得出公式的结果。 上面的代码展示了如何使用 SUM(求和)、AVG(求平均值)、MAX(获取最大值)和 MIN(获取最小值)公式。


7. 设置工作表和打印属性 ##

7.1. 设置工作表属性 ###

工作表属性包括冻结行和列以及用密码保护工作表。 此内容如下所示:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-10.cs
workSheet.ProtectSheet("Password");
workSheet.CreateFreezePane(0, 1);
workSheet.ProtectSheet("Password")
workSheet.CreateFreezePane(0, 1)
$vbLabelText   $csharpLabel

第一行已冻结,将不会随着工作表的其余部分滚动。 工作表也受到密码保护,不允许进行任何编辑。 图 7 和图 8 展示了这一过程。

Freeze Panes related to 7.1. 设置工作表属性 ###

Figure 7Freeze Panes

Protected Worksheet related to 7.1. 设置工作表属性 ###

Figure 8Protected Worksheet

7.2. 设置页面和打印属性 ###

您可以设置页面属性,例如页面的方向、页面的大小以及打印区域等等。

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-11.cs
workSheet.SetPrintArea("A1:L12");
workSheet.PrintSetup.PrintOrientation = IronXL.Printing.PrintOrientation.Landscape;
workSheet.PrintSetup.PaperSize = IronXL.Printing.PaperSize.A4;
workSheet.SetPrintArea("A1:L12")
workSheet.PrintSetup.PrintOrientation = IronXL.Printing.PrintOrientation.Landscape
workSheet.PrintSetup.PaperSize = IronXL.Printing.PaperSize.A4
$vbLabelText   $csharpLabel

打印区域设置为 A1 至 L12。方向设置为横向,纸张大小设置为 A4

Print Setup related to 7.2. 设置页面和打印属性 ###

Figure 9Print Setup


8. 保存工作簿

要保存工作簿,请使用以下代码:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-12.cs
workBook.SaveAs("Budget.xlsx");
workBook.SaveAs("Budget.xlsx")
$vbLabelText   $csharpLabel

教程快速访问

Brand Visual Studio related to 教程快速访问

Download this Tutorial as C# Source Code

The full free C# for Excel Source Code for this tutorial is available to download as a zipped Visual Studio 2017 project file.

Download

Explore this Tutorial on GitHub

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

Use this code as an easy way to get up and running in just a few minutes. The project is saved as a Microsoft Visual Studio 2017 project, but is compatible with any .NET IDE.

How to Create Excel File in C# on GitHub
Github Icon related to 教程快速访问
Documentation related to 教程快速访问

阅读《XL 应用程序接口参考

探索 IronXL 的 API 参考,其中概述了 IronXL 的所有功能、命名空间、类、方法字段和枚举的详细信息。

查看 API 参考
Jonas是一家位于慕尼黑的.NET软件公司的首席开发人员。Jonas使用IronXL来推动客户的会计和销售管道Excel文档之间的数据交换。IronXL正在成为Jonas许多客户会计系统项目中的常用工具。
乔纳斯·施密特
C#开发者

Jonas是一位位于慕尼黑的.NET软件公司首席开发人员。Jonas使用IronXL推动客户的会计和销售管道Excel文档之间的数据交换。IronXL在许多Jonas的客户会计系统项目中正成为一种常用工具。