C# 建立 Excel 文件教程

Jonas 是慕尼黑一家 .NET 軟體公司的首席開發人員。Jonas 使用 IronXL 來驅動客戶的會計和銷售流水線 Excel 文件之間的數據交換。IronXL 正成為 Jonas 許多客戶會計系統項目中的常用工具。
喬納斯·施密特
2019年5月26日
已更新 2024年12月10日
分享:
This article was translated from English: Does it need improvement?
Translated
View the article in English

本教學將一步一步指導您如何在任何支持 .NET Framework 4.5 或 .NET Core 的平台上創建 Excel 工作簿文件。 即使不依賴傳統的Microsoft.Office.Interop.Excel庫,在 C# 中創建 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. 下載免費的 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

    Figure 3Project menu

    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. 按Enter键

  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. 在下一個畫面上,如圖2所示選擇Web Forms。

    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

您只需將特定單元格的值屬性設置為要輸入到單元格中的字段名稱。


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 API 參考資料

查看 IronXL 的 API 參考文件,詳述 IronXL 的所有功能、命名空間、類別、方法字段和列舉。

查看 API 參考資料
Jonas 是慕尼黑一家 .NET 軟體公司的首席開發人員。Jonas 使用 IronXL 來驅動客戶的會計和銷售流水線 Excel 文件之間的數據交換。IronXL 正成為 Jonas 許多客戶會計系統項目中的常用工具。
喬納斯·施密特
C# 開發者

Jonas 是慕尼黑一家 .NET 軟體公司的首席開發人員。Jonas 使用 IronXL 來促進客戶的會計和銷售管道 Excel 文件之間的數據交換。IronXL 正逐漸成為許多 Jonas 客戶會計系統專案中的常用工具。