C# 创建 Excel 文件教程

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 在 .NET 中创建 C# Excel 文件

IronXL 是一款直观的 C# 和 VB Excel 应用程序接口 它能让你在.NET中以闪电般的速度读取、编辑和创建 Excel 电子表格文件。无需安装 MS Office,甚至无需安装 Excel Interop。

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

IronXL 功能:

  • 由我们的 .NET 开发团队直接提供人力支持
  • 使用 Microsoft Visual Studio 快速安装

  • 开发免费。许可证来自 $599。

创建并保存 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")
VB   C#

步骤 1

1. 下载免费的 IronXL C# 库

适用于Excel的C# NuGet库

安装使用 NuGet

Install-Package IronXL.Excel
Java PDF JAR

下载 DLL

下载DLL

手动安装到你的项目中

适用于Excel的C# NuGet库

安装使用 NuGet

Install-Package IronXL.Excel
Java PDF JAR

下载 DLL

下载DLL

手动安装到你的项目中

开始在您的项目中使用IronPDF,并立即获取免费试用。

第一步:
green arrow pointer

查看 IronXLNuget 用于快速安装和部署。它有超过800万次下载,正在使用C#改变Excel。

适用于Excel的C# NuGet库 nuget.org/packages/IronXL.Excel/
Install-Package IronXL.Excel

考虑安装 IronXL DLL 直接。下载并手动安装到您的项目或GAC表单中: IronXL.zip

手动安装到你的项目中

下载DLL

使用 NuGet 安装

安装 IronXL NuGet 软件包有三种不同方法:

1.Visual Studio

2.开发人员命令提示符

3.直接下载 NuGet 软件包

Visual Studio

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

图 3 - 项目菜单

图 4 - 右键单击解决方案资源管理器


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


图 5 - 安装 IronXL.Excel NuGet 软件包

开发人员命令提示符

打开开发人员命令提示符,然后按照以下步骤安装 IronXL.Excel NuGet 软件包:

1.搜索 "开发人员命令提示符"--它通常位于 Visual Studio 文件夹下

2.键入以下命令

3.PM > 安装软件包 IronXL.Excel

4.按回车键

5.软件包将被安装。

6.重新加载 Visual Studio 项目

直接下载 NuGet 软件包

要下载 NuGet 软件包,请执行以下几个步骤:

1.导航至以下 URL:https://www.nuget.org/packages/ironxl.excel/

2.点击下载软件包

3.下载软件包后,双击

4.重新加载 Visual Studio 项目

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

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

图 6 - 下载 IronXL 资料库

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

1.右键单击解决方案资源管理器中的解决方案

2.选择引用

3.浏览 IronXL.dll 库

4.点击确定

我们走

设置完成后,我们就可以开始使用 IronXL 库中的超强功能了!


教程

2.创建 ASP.NET 项目

使用以下步骤创建 ASP.NET 网站

1.打开 Visual Studio

2.点击文件 > 新建项目

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

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


图 1 - 新项目*

5.点击确定

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


图 2 - 网络表格*


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)
VB   C#

两种 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")
VB   C#

上述代码片段中的 "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"
VB   C#

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

4.2.动态设置单元格值

动态设置单元格值与上一段代码几乎相似。这样做的好处是不必硬编码单元格位置。在下一个代码示例中,您将创建一个新的随机对象来创建随机数,然后使用 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
VB   C#

从 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
VB   C#

您只需将特定单元格的 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")
VB   C#

将单元格区域的背景颜色设置为灰色。颜色以 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
VB   C#

在上述代码中,我为单元格 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
VB   C#

这样做的好处是可以设置单元格的数据类型,从而设置公式的结果。上面的代码展示了如何使用 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)
VB   C#

第一行被冻结,不会与工作表的其他部分一起滚动。工作表还受到密码保护,无法进行任何编辑。图 7 和图 8 显示了这一操作。

图 7 - 冻结窗格

图 8 - 受保护工作表

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
VB   C#

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

图 9 - 打印设置


8.保存工作簿

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

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

教程快速访问

将本教程下载为 C&num;源代码

本教程的完整免费 C# for Excel 源代码以压缩的 Visual Studio 2017 项目文件形式提供下载。

下载

在 GitHub 上探索此教程

GitHub 上有该项目的 C&num 和 VB.NET 源代码。

使用此代码,只需几分钟就能轻松上手并运行。该项目保存为 Microsoft Visual Studio 2017 项目,但兼容任何 .NET IDE。

如何用 C&num 在 GitHub 上创建 Excel 文件

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

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

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

乔纳斯·施密特

C#开发者

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