如何在 C# 中建立 Excel 檔案(.NET 教學)
我合作的大多數團隊需要生成Excel文件的頻率至少與他們讀取的頻率相當:發票、匯出、財務團隊可以打開和篩選的每月報告。 我已在主控台應用程式、ASP.NET服務和背景工作者中建置這套流程數十次。 IronXL的API接近Excel本身的思維方式,程式碼讀起來像規範,但在API表面呈現的格式和儲存決策上有幾個重要的選擇。 本指南是我實際在生產中生成XLSX文件的方式,包括最初幾次讓我耗費時間的陷阱。
程式庫可在.NET 8, .NET 9, .NET Core 和 .NET Framework 上執行,支援Windows、Linux、macOS、Azure 和 AWS,不需要在主機上安裝Microsoft Office。下面的程式碼路徑在所有這些目標上都是一致的。
快速開始:建立Excel文件三行即可建立一個新的活頁簿,在A1中寫入值,並將文件儲存到磁碟。 無需啟動 Excel 處理程序,無需COM封送。
-
1使用 IronXL 安裝 NuGet Package Manager
-
2複製並運行這段程式碼。
WorkBook book = IronXL.WorkBook.Create(IronXL.ExcelFileFormat.XLSX); book.CreateWorkSheet("Sheet1")["A1"].Value = "Hello World"; book.SaveAs("MyFile.xlsx");Dim book As WorkBook = IronXL.WorkBook.Create(IronXL.ExcelFileFormat.XLSX) book.CreateWorkSheet("Sheet1")("A1").Value = "Hello World" book.SaveAs("MyFile.xlsx")Dim book As WorkBook = IronXL.WorkBook.Create(IronXL.ExcelFileFormat.XLSX) book.CreateWorkSheet("Sheet1")("A1").Value = "Hello World" book.SaveAs("MyFile.xlsx") -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronXL,並使用 免費試用
最小工作流程(5 個步驟)
- 下載並安裝 IronXL C# 程式庫
- 設定您的.NET專案
- 建立一個
Workbook和Worksheet - 設定儲存格值,格式和公式
- 儲存您的Excel文件
什麼是 IronXL?為什麼要使用它來建立 Excel 檔案?
IronXL 是一個用於讀取、編輯和建立試算表文件的 C# 和 VB.NET Excel API。 它不需要 Microsoft Office 或 Excel Interop,這樣可以將部署壓縮為一個 NuGet 參考和一個 using 指令。
IronXL 完全支援 .NET 9、.NET 8、.NET Core、.NET Framework、Xamarin、行動裝置、Linux、macOS 和 Azure 環境。
IronXL 功能
- 由我們的 .NET 開發團隊直接提供人工支援
- 使用 Microsoft Visual Studio 快速安裝
- 免費用於開發。 授權來自於 $999
如何快速建立並儲存Excel檔案?
透過 NuGet 安裝 IronXL 或 直接下載 DLL。 WorkBook 類別是所有 Excel 操作的入口點,WorkSheet 類別提供操控單個工作表的方法。 完整的逐步指南從下面的第1步開始。
如何安裝 IronXL C# 函式庫?
透過Visual Studio中的NuGet 套件管理員安裝IronXL,或使用套件管理員主控台:
透過專案選單或在方案總管中右鍵單擊您的專案來存取NuGet 套件管理員。

圖3 - 透過專案選單存取NuGet 套件管理員

圖4 - 方案總管中右鍵快顯選單
在套件列表瀏覽 IronXL.Excel,然後點擊安裝。

圖5 - 透過NuGet 套件管理員安裝IronXL.Excel
或者,直接下載 IronXL DLL 並透過方案總管 > 參考 > 瀏覽 IronXL.dll 作為參考新增到您的專案。

圖6 - 從官網下載IronXL程式庫
如何設定我的.NET專案?
IronXL 可以適用於任何 .NET 專案類型: 主控台應用、ASP.NET 網頁應用、API 或桌面工具。 下面的例子使用ASP.NET網頁應用程式,但相同的程式碼路徑適用於所有專案模板。
請依照下列步驟建立 ASP.NET 網站:
-
開啟 Visual Studio
-
點擊檔案 > 新專案
-
在「專案類型」清單中,選擇「Visual C#」下的「Web」。
-
選擇 ASP.NET Web 應用程式

圖 1 - 建立新的 ASP.NET 專案
-
按一下“確定”
-
選擇 Web 表單模板

圖 2 - 選擇 Web Forms 範本
-
按一下“確定”
專案準備就緒後,安裝 IronXL 即可開始以程式設計方式建立 Excel 檔案。
如何在 C# 中建立 Excel 活頁簿?
一個新的活頁簿是透過單次呼叫 WorkBook.Create 建立的,文件格式以列舉常數的形式傳入:
WorkSheet workSheet = workBook.CreateWorkSheet("2020 Budget");WorkSheet workSheet = workBook.CreateWorkSheet("2020 Budget");Dim workSheet As WorkSheet = workBook.CreateWorkSheet("2020 Budget")Dim workSheet As WorkSheet = workBook.CreateWorkSheet("2020 Budget")Create 方法支援 XLS (Excel 97-2003) 和 XLSX (Excel 2007+) 格式。 建議使用 XLSX 格式以獲得更好的效能和更小的檔案大小。
- XLSX: 建議用於所有現代 Excel 版本 (2007+) - 文件更小,效能更好
- XLS: 與 Excel 97-2003 兼容的舊格式
如何將工作表新增到我的活頁簿中?
透過 CreateWorkSheet 新增工作表:
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";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"活頁簿包含一或多張工作表。 每個工作表都由列和欄組成,儲存格位於列和欄的交叉點。 使用 CreateWorkSheet 方法將新工作表新增到您的活頁簿。
WorkBook.CreateWorkSheet(String):新增具有指定標籤名的新工作表WorkSheet:按名稱擷取現有的工作表- 工作表名稱在活頁簿中必須唯一
如何在Excel中設定儲存格值?
如何手動設定儲存格值?
儲存格存取使用與 Excel 相同的 A1 樣式位址字串:
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);
}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 iDim 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 iValue 屬性接受多種資料類型,包括字串、數字、日期和布林值。 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' Initialize random number generator for sample data
Dim r As New Random()
' Populate cells with random budget data for each month
For i As Integer = 2 To 11
' 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
Next i
' Alternative: Set range of cells with same value
workSheet("A13:L13").Value = 0 ' Initialize totals row' Initialize random number generator for sample data
Dim r As New Random()
' Populate cells with random budget data for each month
For i As Integer = 2 To 11
' 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
Next i
' Alternative: Set range of cells with same value
workSheet("A13:L13").Value = 0 ' Initialize totals row字串插值 ($"...") 使得動態引用儲存格變得簡單。 Item 索引器支援單個儲存格和範圍。
如何從資料庫填充Excel?
將資料庫中的資料匯入Excel是一項常見需求:
workSheet["A1:L1"].Style.SetBackgroundColor("#d3d3d3");workSheet["A1:L1"].Style.SetBackgroundColor("#d3d3d3");workSheet("A1:L1").Style.SetBackgroundColor("#d3d3d3")workSheet("A1:L1").Style.SetBackgroundColor("#d3d3d3")此範例示範如何從資料庫將資料讀入 Excel、套用格式,並使用公式進行計算。FormatString 屬性讓您能像在 Excel 中一樣自訂數字格式。
如何將格式應用到Excel儲存格?
如何在Excel中設定背景顏色?
背景、交替列顏色和字型顏色覆蓋都透過儲存格或範圍上的 Style 物件進行:
// 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.SetColor("#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.SetColor("#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.SetColor("#FFFFFF") ' White text
' Create alternating row colors for better readability
For row As Integer = 2 To 11
If row Mod 2 = 0 Then
workSheet($"A{row}:L{row}").Style.SetBackgroundColor("#F2F2F2")
End If
Next row' 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.SetColor("#FFFFFF") ' White text
' Create alternating row colors for better readability
For row As Integer = 2 To 11
If row Mod 2 = 0 Then
workSheet($"A{row}:L{row}").Style.SetBackgroundColor("#F2F2F2")
End If
Next rowSetBackgroundColor 方法接受十六進位色碼。 將背景色和 Font.SetColor 搭配使用以保持在較深填充上的可讀對比。
如何在Excel中建立邊框?
邊界有助於定義資料區域並改善資料結構:
// 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
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' 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 = minIronXL 支援多種 邊框類型,包括細、中、粗、雙線、點狀和虛線。 邊框的每一邊都可以獨立設定樣式。
如何在 C# 中使用 Excel 公式?
IronXL 會在寫入時計算 Excel 公式,因此活頁簿儲存後的值便是正確的:
// 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
workBook.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
workBook.EvaluateAll();' Use built-in aggregation functions for ranges
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 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
workBook.EvaluateAll()' Use built-in aggregation functions for ranges
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 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
workBook.EvaluateAll()Range 類別提供了如 Sum、Average、Max 和 Min 等方法用於快速計算。 對於更複雜的情況,使用 Formula 屬性直接設定 Excel 公式。
.Sum()、.Avg()、.Max() 和 .Min(),而非在處理範圍時使用原始公式字串。 它們是類型安全的,並避免在編譯時出現公式語法錯誤。如何設定工作表和列印屬性?
使用 IronXL 保護單一工作表、凍結列和欄,以及設定列印格式選項。
如何設定工作表屬性?
保護工作表並控制檢視選項:
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;workSheet.SetPrintArea("A1:L12")
workSheet.PrintSetup.PrintOrientation = IronXL.Printing.PrintOrientation.Landscape
workSheet.PrintSetup.PaperSize = IronXL.Printing.PaperSize.A4workSheet.SetPrintArea("A1:L12")
workSheet.PrintSetup.PrintOrientation = IronXL.Printing.PrintOrientation.Landscape
workSheet.PrintSetup.PaperSize = IronXL.Printing.PaperSize.A4工作表保護可防止意外修改,而 凍結窗格 可在捲動時保持重要的列或欄可見。

圖7 - 凍結的標頭列在捲動時保持可見

圖8 - 密碼保護防止未經授權的編輯
如何設定頁面和列印設定?
列印佈局選項(方向、紙張大小、邊距、縮放、頁首、頁尾)都透過 WorkSheet.PrintSetup 提供:
workBook.SaveAs("Budget.xlsx");workBook.SaveAs("Budget.xlsx");workBook.SaveAs("Budget.xlsx")workBook.SaveAs("Budget.xlsx")IPrintSetup 類別提供匹配 Excel 列印設定的完整列印設定選項。

圖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 as CSV — IronXL writes UTF-8 by default
workBook.SaveAsCsv("Budget_UTF8.csv");// 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 as CSV — IronXL writes UTF-8 by default
workBook.SaveAsCsv("Budget_UTF8.csv");' 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 stream As New MemoryStream()
workBook.SaveAs(stream)
Dim excelData As Byte() = stream.ToArray()
' Send to client or save to cloud
End Using
' Save as CSV — IronXL writes UTF-8 by default
workBook.SaveAsCsv("Budget_UTF8.csv")' 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 stream As New MemoryStream()
workBook.SaveAs(stream)
Dim excelData As Byte() = stream.ToArray()
' Send to client or save to cloud
End Using
' Save as CSV — IronXL writes UTF-8 by default
workBook.SaveAsCsv("Budget_UTF8.csv")IronXL 支援多種 匯出格式,包括 XLSX、XLS、CSV、TSV 和 JSON。 Save 方法從文件副檔名選擇格式。
- XLSX / XLS: 完整的 Excel 格式,含格式化、公式和多個工作表
- CSV: 用於資料互換的純文字,每個文件包含一個工作表
- JSON: 用於 web API 和資料管道的結構化輸出
- 串流: 在記憶體中輸出,適用於 web 下載或雲端儲存
實際生成需要多長時間?
對於大多數正式環境匯出作業常見的活頁簿大小(約 10,000 列和少數幾欄),處理程序完成暖機後,產生檔案並以單次 SaveAs 儲存至磁碟,通常可在一秒內完成。新處理程序首次執行時較慢,主要耗時在 IronXL 組件載入及 JIT 暖機;後續執行時間則較短且相對穩定,僅會因背景活動而略有差異。確切時間取決於環境,請在自己的目標硬體上測量。下方 CreateExcelBenchmark 範例 提供可重現的測試工具,讓您自行驗證。
對於顯著更大的活頁簿(數十萬列、多個工作表、大量樣式),將整個活頁簿寫入記憶體,並在最後單次呼叫 SaveAs。 我們看到最常見的 “為什麼我的匯出這麼慢?” 問題是,在活頁簿增大的過程中,在循環中多次呼叫 SaveAs:每次儲存都會序列化當前的所有狀態,因此每次迭代的成本會增加。
常見陷阱
有幾件事情常常困擾著人們,因此它們值得一個專門的段落。
忘記在日期和貨幣上使用 FormatString
我看到最多的格式化陷阱:將 .Value 設定為 DateTime,但忘記 FormatString。 日期儲存正確,但 Excel 將其顯示為原始序列號(45292 代表 2024-01-01),直到您應用格式字串如 "yyyy-MM-dd"。 貨幣有完全相同的問題:數目是正確的,但沒有 "$#,##0.00" 它會呈現為一個未格式化的小數。 我現在是在相鄰行寫下值和格式,因此兩者不會分開:
var dateCell = sheet["A2"];
dateCell.Value = DateTime.Today;
dateCell.FormatString = "yyyy-MM-dd";
var moneyCell = sheet["B2"];
moneyCell.Value = 1499.95m;
moneyCell.FormatString = "$#,##0.00";var dateCell = sheet["A2"];
dateCell.Value = DateTime.Today;
dateCell.FormatString = "yyyy-MM-dd";
var moneyCell = sheet["B2"];
moneyCell.Value = 1499.95m;
moneyCell.FormatString = "$#,##0.00";Dim dateCell = sheet("A2")
dateCell.Value = DateTime.Today
dateCell.FormatString = "yyyy-MM-dd"
Dim moneyCell = sheet("B2")
moneyCell.Value = 1499.95D
moneyCell.FormatString = "$#,##0.00"Dim dateCell = sheet("A2")
dateCell.Value = DateTime.Today
dateCell.FormatString = "yyyy-MM-dd"
Dim moneyCell = sheet("B2")
moneyCell.Value = 1499.95D
moneyCell.FormatString = "$#,##0.00"XLS 將在 65,536 列處悄然截斷
本文前面的格式選擇段落已提過此限制,但仍值得在此提醒,因為這類失敗不會發出任何通知:ExcelFileFormat.XLS 每張工作表最多支援 65,536 列,超出限制的列會被捨棄,且不會產生例外或警告。匯出雖然「成功」,資料卻已遺失。處理大量資料時,除非下游系統確實無法讀取 XLSX,否則請選擇 XLSX。
「Excel表示文件損壞」
如果產生的檔案無法開啟,或 Excel 表示檔案已損毀,原因幾乎都是以下兩者之一:檔案串流未正確釋放,導致磁碟上的位元組資料遭到截斷;或寫入的路徑仍被上一次執行鎖定,導致只有部分資料成功寫入。請確保 SaveAs(或包裝它的串流)完全執行完畢後,才讓其他程式存取檔案。將活頁簿寫入任何 MemoryStream 或 FileStream 時,建議使用 using 區塊管理串流。
基準數字的範例專案
如果您想再現之前的時間資料,測試工具是個小型.NET 9主控台應用程式:
// CreateExcelBenchmark/Program.cs (excerpt)
IronXL.License.LicenseKey = Environment.GetEnvironmentVariable("IRONXL_LICENSE_KEY");
var sw = Stopwatch.StartNew();
var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
var sheet = workbook.CreateWorkSheet("Data");
sheet["A1"].Value = "Id";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Amount";
for (int i = 0; i < 10_000; i++)
{
int row = i + 2;
sheet[$"A{row}"].Value = i + 1;
sheet[$"B{row}"].Value = $"Item {i + 1}";
sheet[$"C{row}"].Value = (i + 1) * 1.25m;
}
workbook.SaveAs("Generated.xlsx");
sw.Stop();
Console.WriteLine($"cold: {sw.Elapsed.TotalMilliseconds:F1} ms");// CreateExcelBenchmark/Program.cs (excerpt)
IronXL.License.LicenseKey = Environment.GetEnvironmentVariable("IRONXL_LICENSE_KEY");
var sw = Stopwatch.StartNew();
var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
var sheet = workbook.CreateWorkSheet("Data");
sheet["A1"].Value = "Id";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Amount";
for (int i = 0; i < 10_000; i++)
{
int row = i + 2;
sheet[$"A{row}"].Value = i + 1;
sheet[$"B{row}"].Value = $"Item {i + 1}";
sheet[$"C{row}"].Value = (i + 1) * 1.25m;
}
workbook.SaveAs("Generated.xlsx");
sw.Stop();
Console.WriteLine($"cold: {sw.Elapsed.TotalMilliseconds:F1} ms");Imports System
Imports System.Diagnostics
Imports IronXL
Module Program
Sub Main()
License.LicenseKey = Environment.GetEnvironmentVariable("IRONXL_LICENSE_KEY")
Dim sw As Stopwatch = Stopwatch.StartNew()
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim sheet As WorkSheet = workbook.CreateWorkSheet("Data")
sheet("A1").Value = "Id"
sheet("B1").Value = "Name"
sheet("C1").Value = "Amount"
For i As Integer = 0 To 9999
Dim row As Integer = i + 2
sheet($"A{row}").Value = i + 1
sheet($"B{row}").Value = $"Item {i + 1}"
sheet($"C{row}").Value = (i + 1) * 1.25D
Next
workbook.SaveAs("Generated.xlsx")
sw.Stop()
Console.WriteLine($"cold: {sw.Elapsed.TotalMilliseconds:F1} ms")
End Sub
End ModuleImports System
Imports System.Diagnostics
Imports IronXL
Module Program
Sub Main()
License.LicenseKey = Environment.GetEnvironmentVariable("IRONXL_LICENSE_KEY")
Dim sw As Stopwatch = Stopwatch.StartNew()
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim sheet As WorkSheet = workbook.CreateWorkSheet("Data")
sheet("A1").Value = "Id"
sheet("B1").Value = "Name"
sheet("C1").Value = "Amount"
For i As Integer = 0 To 9999
Dim row As Integer = i + 2
sheet($"A{row}").Value = i + 1
sheet($"B{row}").Value = $"Item {i + 1}"
sheet($"C{row}").Value = (i + 1) * 1.25D
Next
workbook.SaveAs("Generated.xlsx")
sw.Stop()
Console.WriteLine($"cold: {sw.Elapsed.TotalMilliseconds:F1} ms")
End Sub
End Module在 dotnet run -c Release 下執行它,並替換為您自己的列數、欄數或樣式以查看活頁簿複雜度對數字的影響。
物件參考和資源
IronXL API 參考 涵蓋本教學涉及的每個類別和方法,也包括未涉及的。
相關Excel操作的其他教學:
總結
IronXL.Excel 生成不依賴於 Microsoft Office 或 Interop 的 XLSX、XLS、CSV 和 JSON 格式的 Excel 活頁簿。我遵循的每個專案的做法相同:建立活頁簿,新增工作表,寫入數值和公式,設定顯示相關的格式字串,並最終儲存一次。
準備好在生產中使用 IronXL 了嗎? 開始您的免費試用 或 查看授權選項。
常見問題
什麼是IronXL,為什麼它對於在C#中創建Excel文件有用?
IronXL是一個C#和VB.NET Excel API,允許開發者讀取、編輯和創建試算表文件,不需要使用Microsoft Office或Excel Interop。它特別適用於在應用程式中生產Excel文件,當您希望利用僅需一個NuGet程式包引用來保持部署簡單時。
如何快速使用IronXL創建並儲存一個Excel文件?
要快速使用IronXL創建並儲存一個Excel文件,首先通過NuGet安裝該程式庫或直接下載DLL,然後使用WorkBook和WorkSheet類來操縱您的Excel工作簿,最後使用SaveAs方法儲存該文件。
IronXL支持哪些平台和框架?
IronXL支持.NET 9、.NET 8、.NET Core、.NET Framework、Xamarin、Mobile、Linux、macOS、Azure和AWS環境,提供多種不同開發和部署場景下的靈活性。
我可以在IronXL創建的Excel文件中格式化儲存格嗎?
是的,使用IronXL,您可以對儲存格應用多種格式,例如設置背景顏色、邊框和自訂的數字格式。您還可以定義複雜的條件格式,使您的數據既實用又美觀。
在使用IronXL創建工作簿時能使用Excel公式嗎?
是的,IronXL允許您直接使用和計算Excel公式。這確保了當工作簿被儲存時,所有公式都已計算完畢,結果會立即反映在Excel文件內。
如何高效管理大型Excel文件與IronXL?
對於大型文件,建議在內存中完整創建工作簿,最後只有一次呼叫SaveAs。這種方法避免了多次文件IO操作的開銷,確保了更快速和高效的工作簿創建過程。
IronXL支持哪些匯出格式?
IronXL支持以多種格式匯出Excel文件,如XLSX、XLS、CSV和JSON,為您提供將創建的數據與其他系統或應用程式整合的廣泛選擇。
IronXL支持在工作表內動態處理數據嗎?
是的,IronXL允許您使用字符串插值和循環結構動態設置儲存格值,促進動態和數據驅動試算表的創建。
如何使用IronXL應用頁面和打印設置?
IronXL的PrintSetup類提供設置打印選項,如方向、紙張大小和邊距,使得從您的程式碼中直接準備文件進行打印變得簡單明瞭。
使用IronXL時有什麼常見的錯誤需要避免?
常見錯誤包括忘記為儲存格設置FormatString,特別是對日期和貨幣,以及使用舊的XLS格式在65,536列時會截斷。正確配置文件流並選擇適當的文件格式可以防止這些問題。
Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。