跳至頁尾內容
USING IRONXL

如何使用 IronXL 在 C# 中產生 Excel 文件

使用C#程式生成Excel試算表文件傳統上需要安裝Microsoft Office或進行複雜的COM互操作。IronXL完全改變了這一切,提供了一個無需任何Office依賴的簡單API來建立Excel文件。 本教程引導您使用IronXL在C#中生成Excel文件,從基本的試算表建立到高級格式化和資料庫整合。 無論您是建立報告、導出資料(XLS或XLSX文件),或者自動化試算表生成,您都將學習在.NET應用程式中使用Excel的基本技術。

如何使用IronXL在C#中生成Excel文件:圖片1 - IronXL

為什麼要在沒有Microsoft Office的情況下生成Excel文件?

開發無Office依賴的Excel生成功能可以解決重要的部署挑戰。 由於授權成本和資源開銷,伺服器環境很少安裝Microsoft Office。 每次Office安裝需要大量磁碟空間和記憶體,這使得它對於雲部署或容器化應用程式來說是不切實際的。

IronXL通過獨立運行來消除這些限制。 您的C# Excel文件生成可以在Windows、Linux、macOS、Docker容器或Azure App Services上運行,無需修改。 這種跨平台相容性意味著您只需建立一次,隨處部署,無論是針對.NET Framework、.NET Core還是.NET 10應用程式。

如何使用IronXL在C#中生成Excel文件:圖片2 - 跨平台

性能在沒有COM互操作開銷的情況下顯著提高。 傳統的Office自動化對每項操作都進行單獨的過程實例的建立,消耗了記憶體和CPU資源。 IronXL在應用程式的進程空間內的記憶體中處理所有事情,當您程式生成Excel文件時,實現更快的執行和更低的資源消耗。

部署變得簡單,因為IronXL作為一個單一的NuGet包發布。 沒有註冊表項,沒有COM註冊,也不需要維護Office服務包。 您的持續整合管道運行順暢無阻,Docker容器保持輕量級。 這種簡化的方法使得IronXL成為受歡迎的選擇,如在各種開發者論壇中專業人士分享他們的Excel自動化經驗。

一些開發人員仍然探索Microsoft的Open XML生產力工具直接處理Office Open XML文件結構。 但這種方法需要更多的手動操作和對XML結構和Open XML SDK安裝的詳細了解。 IronXL消除了這些複雜性,讓您有一個更快速的方法程式化地使用Excel。

如何使用IronXL在C#中生成Excel文件:圖片3 - 功能

如何在C#專案中安裝IronXL?

通過Visual Studio中的NuGet包管理器安裝IronXL只需片刻。 右鍵點擊解決方案瀏覽器中的專案,然後選擇"管理NuGet封裝"。搜尋"IronXL.Excel"並點擊安裝。 該包會自動包含生成C# Excel文件所需的所有依賴項。

要通過包管理器控制台或.NET CLI安裝,請使用以下任一命令:

Install-Package IronXL.Excel

如何使用IronXL在C#中生成Excel文件:圖片4 - 安裝

通過這個簡單的測試來驗證安裝,以確認庫已經就緒:

using IronXL;
// Create an in-memory workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");
using IronXL;
// Create an in-memory workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");
Imports IronXL

' Create an in-memory workbook
Dim workbook = WorkBook.Create()
Console.WriteLine("IronXL installed successfully!")
$vbLabelText   $csharpLabel

如果這次運行沒有錯誤,IronXL即可使用。 該庫支持所有現代的.NET版本,確保與您現有專案的相容性。 有關詳細的安裝指導和故障排除,請參閱官方NuGet安裝文件

輸出

如何使用IronXL在C#中生成Excel文件:圖片5 - 控制台輸出

如何建立您的第一個Excel文件?

使用IronXL建立Excel文件從WorkBook類開始,這是您所有Excel操作的入口。 該庫同時支持現代XLSX和遺留XLS格式,這樣在您建立Excel文件時提供不同需求的靈活性。

using IronXL;
// Create a new workbook (XLSX format by default)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add metadata
workbook.Metadata.Title = "Monthly Sales Report";
workbook.Metadata.Author = "Sales Department";
workbook.Metadata.Comments = "Generated using IronXL";
// Create a worksheet
WorkSheet worksheet = workbook.CreateWorkSheet("January Sales");
// Add header row
worksheet["A1"].Value = "Date";
worksheet["B1"].Value = "Product";
worksheet["C1"].Value = "Quantity";
worksheet["D1"].Value = "Revenue";
// Add data rows
worksheet["A2"].Value = new DateTime(2024, 1, 15);
worksheet["B2"].Value = "Widget Pro";
worksheet["C2"].Value = 100;
worksheet["D2"].Value = 2500.00;
// Save the workbook
workbook.SaveAs("FirstExcelFile.xlsx");
using IronXL;
// Create a new workbook (XLSX format by default)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add metadata
workbook.Metadata.Title = "Monthly Sales Report";
workbook.Metadata.Author = "Sales Department";
workbook.Metadata.Comments = "Generated using IronXL";
// Create a worksheet
WorkSheet worksheet = workbook.CreateWorkSheet("January Sales");
// Add header row
worksheet["A1"].Value = "Date";
worksheet["B1"].Value = "Product";
worksheet["C1"].Value = "Quantity";
worksheet["D1"].Value = "Revenue";
// Add data rows
worksheet["A2"].Value = new DateTime(2024, 1, 15);
worksheet["B2"].Value = "Widget Pro";
worksheet["C2"].Value = 100;
worksheet["D2"].Value = 2500.00;
// Save the workbook
workbook.SaveAs("FirstExcelFile.xlsx");
Imports IronXL

' Create a new workbook (XLSX format by default)
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

' Add metadata
workbook.Metadata.Title = "Monthly Sales Report"
workbook.Metadata.Author = "Sales Department"
workbook.Metadata.Comments = "Generated using IronXL"

' Create a worksheet
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("January Sales")

' Add header row
worksheet("A1").Value = "Date"
worksheet("B1").Value = "Product"
worksheet("C1").Value = "Quantity"
worksheet("D1").Value = "Revenue"

' Add data rows
worksheet("A2").Value = New DateTime(2024, 1, 15)
worksheet("B2").Value = "Widget Pro"
worksheet("C2").Value = 100
worksheet("D2").Value = 2500.0

' Save the workbook
workbook.SaveAs("FirstExcelFile.xlsx")
$vbLabelText   $csharpLabel

此程式碼演示了幾個建立Excel文件的關鍵概念。 WorkBook.Create()方法在記憶體中初始化一個新的Excel文件。 您可以使用ExcelFileFormat枚舉來指定格式——選擇XLSX以達到現代Excel相容性或選擇XLS以獲得舊版支持。 Metadata屬性允許您嵌入文件資訊,這些資訊會顯示在Excel的文件屬性中,符合Microsoft的文件屬性標準

CreateWorkSheet()方法新增了一個帶指定名稱的新工作表。 Excel熟悉的單元格符號(例如A1、B1等)使得設置值變得直觀。IronXL自動處理資料型別轉換,能識別日期、數字和文字而無需顯式型別轉換。 SaveAs()方法將完整的Excel文件寫入磁碟。 有關更多工作表操作,請參閱如何撰寫Excel文件指南

輸出

如何使用IronXL在C#中生成Excel文件:圖片6 - 基本Excel輸出

如何將資料寫入Excel單元格?

IronXL提供多種方法來填充Excel單元格,從個別單元格指定到大範圍操作。 理解這些方法將幫助您為資料場景選擇最有效的方式寫入Excel文件

using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Individual cell assignment
worksheet["A1"].Value = "Employee Name";
worksheet["A2"].Value = "John Smith";
worksheet["A3"].Value = "Jane Doe";
// Range assignment for multiple cells at once
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based row, 0-based column)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales");       // C2
worksheet.SetCellValue(2, 2, "Marketing");   // C3
// Array-based header population
string[] headers = { "ID", "Name", "Email", "Phone" };
for (int i = 0; i < headers.Length; i++)
{
    worksheet.SetCellValue(0, i, headers[i]);
}
// Working with different data types
worksheet["E1"].Value = "Salary";
worksheet["E2"].Value = 75000.50m;  // Decimal for currency
worksheet["E3"].Value = 82000.75m;
worksheet["F1"].Value = "Start Date";
worksheet["F2"].Value = new DateTime(2020, 3, 15);
worksheet["F3"].Value = new DateTime(2019, 7, 1);
worksheet["G1"].Value = "Full Time";
worksheet["G2"].Value = true;  // Boolean
worksheet["G3"].Value = true;
workbook.SaveAs("EmployeeData.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Individual cell assignment
worksheet["A1"].Value = "Employee Name";
worksheet["A2"].Value = "John Smith";
worksheet["A3"].Value = "Jane Doe";
// Range assignment for multiple cells at once
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based row, 0-based column)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales");       // C2
worksheet.SetCellValue(2, 2, "Marketing");   // C3
// Array-based header population
string[] headers = { "ID", "Name", "Email", "Phone" };
for (int i = 0; i < headers.Length; i++)
{
    worksheet.SetCellValue(0, i, headers[i]);
}
// Working with different data types
worksheet["E1"].Value = "Salary";
worksheet["E2"].Value = 75000.50m;  // Decimal for currency
worksheet["E3"].Value = 82000.75m;
worksheet["F1"].Value = "Start Date";
worksheet["F2"].Value = new DateTime(2020, 3, 15);
worksheet["F3"].Value = new DateTime(2019, 7, 1);
worksheet["G1"].Value = "Full Time";
worksheet["G2"].Value = true;  // Boolean
worksheet["G3"].Value = true;
workbook.SaveAs("EmployeeData.xlsx");
Imports IronXL

Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("Employees")
' Individual cell assignment
worksheet("A1").Value = "Employee Name"
worksheet("A2").Value = "John Smith"
worksheet("A3").Value = "Jane Doe"
' Range assignment for multiple cells at once
worksheet("B1:B3").Value = "Active"
' Using numeric indices (0-based row, 0-based column)
worksheet.SetCellValue(0, 2, "Department") ' C1
worksheet.SetCellValue(1, 2, "Sales") ' C2
worksheet.SetCellValue(2, 2, "Marketing") ' C3
' Array-based header population
Dim headers As String() = {"ID", "Name", "Email", "Phone"}
For i As Integer = 0 To headers.Length - 1
    worksheet.SetCellValue(0, i, headers(i))
Next
' Working with different data types
worksheet("E1").Value = "Salary"
worksheet("E2").Value = 75000.5D ' Decimal for currency
worksheet("E3").Value = 82000.75D
worksheet("F1").Value = "Start Date"
worksheet("F2").Value = New DateTime(2020, 3, 15)
worksheet("F3").Value = New DateTime(2019, 7, 1)
worksheet("G1").Value = "Full Time"
worksheet("G2").Value = True ' Boolean
worksheet("G3").Value = True
workbook.SaveAs("EmployeeData.xlsx")
$vbLabelText   $csharpLabel

程式碼展示了IronXL靈活的單元格位址。 字串符號("A1")對Excel使用者來說非常自然,而數字索引為迴圈和動態生成提供了程式控制。 範圍指定("B1:B3")高效地將多個單元格設置為相同的值,適用於初始化列或應用預設值。

IronXL智能地處理不同的資料型別。小數保持精確度以適應金融資料,DateTime物件格式化正確地被作為Excel日期,布林則顯示為TRUE/FALSE。 這種自動轉換消除了手動格式程式碼,同時確保資料完整性。 對於大資料集,探索導入資料指南以獲取額外的模式。

輸出

如何使用IronXL在C#中生成Excel文件:圖片7 - Excel輸出

如何應用專業格式到Excel文件?

專業的Excel文件需要的不僅僅是原始資料。 IronXL的風格化API將普通的試算表轉變為通過格式化、顏色和可視化層次結構處理的商業文件。 您可以應用單元格格式化來控制試算表的每一個可視面向。

using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Header formatting
var headerRange = worksheet["A1:D1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.Font.Height = 12;
headerRange.Style.SetBackgroundColor("#4472C4");
headerRange.Style.Font.Color = "#FFFFFF";
// Column width adjustment
worksheet.AutoSizeColumn(0); // Auto-fit column A
worksheet.GetColumn(1).Width = 20; // Set column B width
// Number formatting
var salaryColumn = worksheet["E2:E3"];
salaryColumn.FormatString = "$#,##0.00";
// Date formatting
var dateColumn = worksheet["F2:F3"];
dateColumn.FormatString = "MM/dd/yyyy";
// Cell borders
var dataRange = worksheet["A1:G3"];
dataRange.Style.TopBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.LeftBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.RightBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.TopBorder.Color = "#000000";
dataRange.Style.BottomBorder.Color = "#000000";
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability (banded rows)
for (int row = 2; row <= 10; row++)
{
    if (row % 2 == 0)
    {
        worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
workbook.SaveAs("FormattedReport.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Header formatting
var headerRange = worksheet["A1:D1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.Font.Height = 12;
headerRange.Style.SetBackgroundColor("#4472C4");
headerRange.Style.Font.Color = "#FFFFFF";
// Column width adjustment
worksheet.AutoSizeColumn(0); // Auto-fit column A
worksheet.GetColumn(1).Width = 20; // Set column B width
// Number formatting
var salaryColumn = worksheet["E2:E3"];
salaryColumn.FormatString = "$#,##0.00";
// Date formatting
var dateColumn = worksheet["F2:F3"];
dateColumn.FormatString = "MM/dd/yyyy";
// Cell borders
var dataRange = worksheet["A1:G3"];
dataRange.Style.TopBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.LeftBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.RightBorder.Type = IronXL.Styles.BorderType.Thin;
dataRange.Style.TopBorder.Color = "#000000";
dataRange.Style.BottomBorder.Color = "#000000";
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability (banded rows)
for (int row = 2; row <= 10; row++)
{
    if (row % 2 == 0)
    {
        worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
workbook.SaveAs("FormattedReport.xlsx");
Imports IronXL

Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("Employees")

' Header formatting
Dim headerRange = worksheet("A1:D1")
headerRange.Style.Font.Bold = True
headerRange.Style.Font.Height = 12
headerRange.Style.SetBackgroundColor("#4472C4")
headerRange.Style.Font.Color = "#FFFFFF"

' Column width adjustment
worksheet.AutoSizeColumn(0) ' Auto-fit column A
worksheet.GetColumn(1).Width = 20 ' Set column B width

' Number formatting
Dim salaryColumn = worksheet("E2:E3")
salaryColumn.FormatString = "$#,##0.00"

' Date formatting
Dim dateColumn = worksheet("F2:F3")
dateColumn.FormatString = "MM/dd/yyyy"

' Cell borders
Dim dataRange = worksheet("A1:G3")
dataRange.Style.TopBorder.Type = IronXL.Styles.BorderType.Thin
dataRange.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin
dataRange.Style.LeftBorder.Type = IronXL.Styles.BorderType.Thin
dataRange.Style.RightBorder.Type = IronXL.Styles.BorderType.Thin
dataRange.Style.TopBorder.Color = "#000000"
dataRange.Style.BottomBorder.Color = "#000000"

' Text alignment
worksheet("A1:G1").Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center

' Alternating row colors for readability (banded rows)
For row As Integer = 2 To 10
    If row Mod 2 = 0 Then
        worksheet($"A{row}:G{row}").Style.SetBackgroundColor("#F2F2F2")
    End If
Next

workbook.SaveAs("FormattedReport.xlsx")
$vbLabelText   $csharpLabel

此格式程式碼建立了一個符合商業標準的專業外觀。 帶有背景顏色的粗體標題建立了可視化層次結構。 SetBackgroundColor()方法接受十六進位色碼,提供對顏色方案的精確控制。 字體屬性包括尺寸、顏色、粗體、斜體和下劃線選項——所有這些都是建立符合企業品牌指南的Excel文件所必需的。

列寬調整可防止文字截斷。 GetColumn().Width則提供精確控制。 數字格式使用Excel的格式碼——例如,"$#,##0.00"顯示帶千位分隔符和兩位小數的貨幣。 日期格式遵循類似的模式,使用標準的Excel日期格式字串,如在Microsoft的數字格式程式碼參考中所記載。

邊框定義資料邊界,提高可讀性。 BorderType枚舉提供不同的風格:薄、中、厚、點和虛線。 交替行顏色,通常稱為"帶狀行",有助於讀者跨寬廣的資料集跟踪資訊。 要了解有關合併單元格和其他佈局功能的更多資訊,參閱合併單元格指南

輸出

如何使用IronXL在C#中生成Excel文件:圖片8 - 格式化Excel輸出

如何程式化地使用Excel公式?

Excel公式通過自動計算為試算表驅動活力。 IronXL支持公式建立和評估,允許動態試算表自動更新。

using IronXL;
var workbook = WorkBook.Create();
// Create a budget worksheet
WorkSheet budget = workbook.CreateWorkSheet("Q1 Budget");
// Headers
budget["A1"].Value = "Category";
budget["B1"].Value = "January";
budget["C1"].Value = "February";
budget["D1"].Value = "March";
budget["E1"].Value = "Q1 Total";
// Budget categories and values
string[] categories = { "Salaries", "Marketing", "Operations", "Equipment", "Training" };
decimal[,] monthlyBudgets = {
    { 50000, 52000, 51000 },
    { 15000, 18000, 20000 },
    { 8000, 8500, 9000 },
    { 12000, 5000, 7000 },
    { 3000, 3500, 4000 }
};
// Populate data and add row total formulas
for (int i = 0; i < categories.Length; i++)
{
    budget[$"A{i + 2}"].Value = categories[i];
    budget[$"B{i + 2}"].Value = monthlyBudgets[i, 0];
    budget[$"C{i + 2}"].Value = monthlyBudgets[i, 1];
    budget[$"D{i + 2}"].Value = monthlyBudgets[i, 2];
    budget[$"E{i + 2}"].Formula = $"=SUM(B{i + 2}:D{i + 2})";
}
// Monthly totals row
budget["A7"].Value = "Monthly Total";
budget["B7"].Formula = "=SUM(B2:B6)";
budget["C7"].Formula = "=SUM(C2:C6)";
budget["D7"].Formula = "=SUM(D2:D6)";
budget["E7"].Formula = "=SUM(E2:E6)";
// Calculate percentages
budget["A9"].Value = "Marketing %";
budget["B9"].Formula = "=B3/B7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas before saving
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");
using IronXL;
var workbook = WorkBook.Create();
// Create a budget worksheet
WorkSheet budget = workbook.CreateWorkSheet("Q1 Budget");
// Headers
budget["A1"].Value = "Category";
budget["B1"].Value = "January";
budget["C1"].Value = "February";
budget["D1"].Value = "March";
budget["E1"].Value = "Q1 Total";
// Budget categories and values
string[] categories = { "Salaries", "Marketing", "Operations", "Equipment", "Training" };
decimal[,] monthlyBudgets = {
    { 50000, 52000, 51000 },
    { 15000, 18000, 20000 },
    { 8000, 8500, 9000 },
    { 12000, 5000, 7000 },
    { 3000, 3500, 4000 }
};
// Populate data and add row total formulas
for (int i = 0; i < categories.Length; i++)
{
    budget[$"A{i + 2}"].Value = categories[i];
    budget[$"B{i + 2}"].Value = monthlyBudgets[i, 0];
    budget[$"C{i + 2}"].Value = monthlyBudgets[i, 1];
    budget[$"D{i + 2}"].Value = monthlyBudgets[i, 2];
    budget[$"E{i + 2}"].Formula = $"=SUM(B{i + 2}:D{i + 2})";
}
// Monthly totals row
budget["A7"].Value = "Monthly Total";
budget["B7"].Formula = "=SUM(B2:B6)";
budget["C7"].Formula = "=SUM(C2:C6)";
budget["D7"].Formula = "=SUM(D2:D6)";
budget["E7"].Formula = "=SUM(E2:E6)";
// Calculate percentages
budget["A9"].Value = "Marketing %";
budget["B9"].Formula = "=B3/B7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas before saving
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");
Imports IronXL

Dim workbook = WorkBook.Create()
' Create a budget worksheet
Dim budget As WorkSheet = workbook.CreateWorkSheet("Q1 Budget")
' Headers
budget("A1").Value = "Category"
budget("B1").Value = "January"
budget("C1").Value = "February"
budget("D1").Value = "March"
budget("E1").Value = "Q1 Total"
' Budget categories and values
Dim categories As String() = {"Salaries", "Marketing", "Operations", "Equipment", "Training"}
Dim monthlyBudgets As Decimal(,) = {
    {50000, 52000, 51000},
    {15000, 18000, 20000},
    {8000, 8500, 9000},
    {12000, 5000, 7000},
    {3000, 3500, 4000}
}
' Populate data and add row total formulas
For i As Integer = 0 To categories.Length - 1
    budget($"A{i + 2}").Value = categories(i)
    budget($"B{i + 2}").Value = monthlyBudgets(i, 0)
    budget($"C{i + 2}").Value = monthlyBudgets(i, 1)
    budget($"D{i + 2}").Value = monthlyBudgets(i, 2)
    budget($"E{i + 2}").Formula = $"=SUM(B{i + 2}:D{i + 2})"
Next
' Monthly totals row
budget("A7").Value = "Monthly Total"
budget("B7").Formula = "=SUM(B2:B6)"
budget("C7").Formula = "=SUM(C2:C6)"
budget("D7").Formula = "=SUM(D2:D6)"
budget("E7").Formula = "=SUM(E2:E6)"
' Calculate percentages
budget("A9").Value = "Marketing %"
budget("B9").Formula = "=B3/B7*100"
' Average calculation
budget("A10").Value = "Average Spending"
budget("B10").Formula = "=AVERAGE(B2:B6)"
' Evaluate all formulas before saving
workbook.EvaluateAll()
workbook.SaveAs("Budget.xlsx")
$vbLabelText   $csharpLabel

這個預算範例展示了公式應用的實用操作。 Formula屬性接受標準的Excel公式語法,以等號開始。 IronXL支持一般函式:SUM, AVERAGE, COUNT, MAX, MIN和許多其他。 公式中的單元格引用完全如在Excel中一樣工作,包括相對和絕對引用。

EvaluateAll()方法處理所有公式,更新整個工作簿中的計算值。 這可以確保公式在文件被打開在Excel中時顯示結果。 在無評估的情況下,Excel將顯示公式文字,直到使用者觸發重新計算。 有關閱讀公式結果的更多資訊,請參閱讀取Excel文件文件

輸出

如何使用IronXL在C#中生成Excel文件:圖片9 - 使用公式的Excel輸出

如何將資料庫資料導出到Excel?

實際應用程式通常將資料庫資料導出到Excel以進行報告和分析。 IronXL通過內建的DataTable支持使這一過程變得簡單,無需從C#應用程式導出Excel時的手動欄位映射。

using System.Data;
using IronXL;

// Simulate database retrieval (replace with actual database code)
DataTable GetSalesData()
{
    DataTable dt = new DataTable("Sales");
    dt.Columns.Add("OrderID", typeof(int));
    dt.Columns.Add("CustomerName", typeof(string));
    dt.Columns.Add("Product", typeof(string));
    dt.Columns.Add("Quantity", typeof(int));
    dt.Columns.Add("UnitPrice", typeof(decimal));
    dt.Columns.Add("OrderDate", typeof(DateTime));
    dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99m, DateTime.Now.AddDays(-5));
    dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99m, DateTime.Now.AddDays(-4));
    dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99m, DateTime.Now.AddDays(-3));
    dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99m, DateTime.Now.AddDays(-2));
    dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99m, DateTime.Now.AddDays(-1));
    return dt;
}

// Export to Excel
WorkBook reportWorkbook = WorkBook.Create();
WorkSheet reportSheet = reportWorkbook.CreateWorkSheet("Sales Report");
DataTable salesData = GetSalesData();

// Title row
reportSheet["A1"].Value = "Order Report - " + DateTime.Now.ToString("MMMM yyyy");
reportSheet.Merge("A1:F1");
reportSheet["A1"].Style.Font.Bold = true;
reportSheet["A1"].Style.Font.Height = 14;

// Headers
int headerRow = 3;
for (int col = 0; col < salesData.Columns.Count; col++)
{
    reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns[col].ColumnName);
}
var headers = reportSheet[$"A{headerRow}:F{headerRow}"];
headers.Style.Font.Bold = true;
headers.Style.SetBackgroundColor("#D9E1F2");

// Data rows
for (int row = 0; row < salesData.Rows.Count; row++)
{
    for (int col = 0; col < salesData.Columns.Count; col++)
    {
        reportSheet.SetCellValue(row + headerRow, col, salesData.Rows[row][col]);
    }
    reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}

// Total header
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency and date columns
reportSheet[$"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";

// Summary section
int summaryRow = headerRow + salesData.Rows.Count + 2;
reportSheet[$"A{summaryRow}"].Value = "Summary";
reportSheet[$"A{summaryRow}"].Style.Font.Bold = true;
reportSheet[$"A{summaryRow + 1}"].Value = "Total Orders:";
reportSheet[$"B{summaryRow + 1}"].Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})";
reportSheet[$"A{summaryRow + 2}"].Value = "Total Revenue:";
reportSheet[$"B{summaryRow + 2}"].Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})";
reportSheet[$"B{summaryRow + 2}"].FormatString = "$#,##0.00";

for (int col = 0; col <= 6; col++) { reportSheet.AutoSizeColumn(col); }
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");
using System.Data;
using IronXL;

// Simulate database retrieval (replace with actual database code)
DataTable GetSalesData()
{
    DataTable dt = new DataTable("Sales");
    dt.Columns.Add("OrderID", typeof(int));
    dt.Columns.Add("CustomerName", typeof(string));
    dt.Columns.Add("Product", typeof(string));
    dt.Columns.Add("Quantity", typeof(int));
    dt.Columns.Add("UnitPrice", typeof(decimal));
    dt.Columns.Add("OrderDate", typeof(DateTime));
    dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99m, DateTime.Now.AddDays(-5));
    dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99m, DateTime.Now.AddDays(-4));
    dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99m, DateTime.Now.AddDays(-3));
    dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99m, DateTime.Now.AddDays(-2));
    dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99m, DateTime.Now.AddDays(-1));
    return dt;
}

// Export to Excel
WorkBook reportWorkbook = WorkBook.Create();
WorkSheet reportSheet = reportWorkbook.CreateWorkSheet("Sales Report");
DataTable salesData = GetSalesData();

// Title row
reportSheet["A1"].Value = "Order Report - " + DateTime.Now.ToString("MMMM yyyy");
reportSheet.Merge("A1:F1");
reportSheet["A1"].Style.Font.Bold = true;
reportSheet["A1"].Style.Font.Height = 14;

// Headers
int headerRow = 3;
for (int col = 0; col < salesData.Columns.Count; col++)
{
    reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns[col].ColumnName);
}
var headers = reportSheet[$"A{headerRow}:F{headerRow}"];
headers.Style.Font.Bold = true;
headers.Style.SetBackgroundColor("#D9E1F2");

// Data rows
for (int row = 0; row < salesData.Rows.Count; row++)
{
    for (int col = 0; col < salesData.Columns.Count; col++)
    {
        reportSheet.SetCellValue(row + headerRow, col, salesData.Rows[row][col]);
    }
    reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}

// Total header
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency and date columns
reportSheet[$"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";

// Summary section
int summaryRow = headerRow + salesData.Rows.Count + 2;
reportSheet[$"A{summaryRow}"].Value = "Summary";
reportSheet[$"A{summaryRow}"].Style.Font.Bold = true;
reportSheet[$"A{summaryRow + 1}"].Value = "Total Orders:";
reportSheet[$"B{summaryRow + 1}"].Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})";
reportSheet[$"A{summaryRow + 2}"].Value = "Total Revenue:";
reportSheet[$"B{summaryRow + 2}"].Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})";
reportSheet[$"B{summaryRow + 2}"].FormatString = "$#,##0.00";

for (int col = 0; col <= 6; col++) { reportSheet.AutoSizeColumn(col); }
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");
Imports System.Data
Imports IronXL

' Simulate database retrieval (replace with actual database code)
Function GetSalesData() As DataTable
    Dim dt As New DataTable("Sales")
    dt.Columns.Add("OrderID", GetType(Integer))
    dt.Columns.Add("CustomerName", GetType(String))
    dt.Columns.Add("Product", GetType(String))
    dt.Columns.Add("Quantity", GetType(Integer))
    dt.Columns.Add("UnitPrice", GetType(Decimal))
    dt.Columns.Add("OrderDate", GetType(DateTime))
    dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99D, DateTime.Now.AddDays(-5))
    dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99D, DateTime.Now.AddDays(-4))
    dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99D, DateTime.Now.AddDays(-3))
    dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99D, DateTime.Now.AddDays(-2))
    dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99D, DateTime.Now.AddDays(-1))
    Return dt
End Function

' Export to Excel
Dim reportWorkbook As WorkBook = WorkBook.Create()
Dim reportSheet As WorkSheet = reportWorkbook.CreateWorkSheet("Sales Report")
Dim salesData As DataTable = GetSalesData()

' Title row
reportSheet("A1").Value = "Order Report - " & DateTime.Now.ToString("MMMM yyyy")
reportSheet.Merge("A1:F1")
reportSheet("A1").Style.Font.Bold = True
reportSheet("A1").Style.Font.Height = 14

' Headers
Dim headerRow As Integer = 3
For col As Integer = 0 To salesData.Columns.Count - 1
    reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns(col).ColumnName)
Next
Dim headers = reportSheet($"A{headerRow}:F{headerRow}")
headers.Style.Font.Bold = True
headers.Style.SetBackgroundColor("#D9E1F2")

' Data rows
For row As Integer = 0 To salesData.Rows.Count - 1
    For col As Integer = 0 To salesData.Columns.Count - 1
        reportSheet.SetCellValue(row + headerRow, col, salesData.Rows(row)(col))
    Next
    reportSheet($"G{row + headerRow + 1}").Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}"
Next

' Total header
reportSheet("G3").Value = "Total"
reportSheet("G3").Style.Font.Bold = True
reportSheet("G3").Style.SetBackgroundColor("#D9E1F2")

' Format currency and date columns
reportSheet($"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}").FormatString = "$#,##0.00"
reportSheet($"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}").FormatString = "$#,##0.00"
reportSheet($"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}").FormatString = "MM/dd/yyyy"

' Summary section
Dim summaryRow As Integer = headerRow + salesData.Rows.Count + 2
reportSheet($"A{summaryRow}").Value = "Summary"
reportSheet($"A{summaryRow}").Style.Font.Bold = True
reportSheet($"A{summaryRow + 1}").Value = "Total Orders:"
reportSheet($"B{summaryRow + 1}").Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})"
reportSheet($"A{summaryRow + 2}").Value = "Total Revenue:"
reportSheet($"B{summaryRow + 2}").Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})"
reportSheet($"B{summaryRow + 2}").FormatString = "$#,##0.00"

For col As Integer = 0 To 6
    reportSheet.AutoSizeColumn(col)
Next
reportWorkbook.EvaluateAll()
reportWorkbook.SaveAs("DatabaseExport.xlsx")
$vbLabelText   $csharpLabel

這個範例展示了完整的資料庫到Excel的工作流程。 DataTable模擬資料庫檢索——在生產中,請用使用Entity Framework、Dapper或ADO.NET的實際資料庫查詢替換這一項。 手動映射方法提供了對格式化和佈局的完全控制,正如Microsoft的資料導出最佳實踐中所建議的那樣。

程式碼建立了一個帶標題、格式化標題行和資料行的專業報告。 公式列動態計算每行的總計。 摘要部分使用Excel公式來計數訂單和總和收入,確保這些值在資料更改時更新。 有關使用DataSet和較大資料結構的詳細資訊,請參見Excel到DataSet轉換指南

輸出

如何使用IronXL在C#中生成Excel文件:圖片10 - 資料庫導出到Excel輸出

需要將Excel報告投入生產? 獲取一個授權以解鎖IronXL在生產部署中的全部潛力。

如何處理多個工作表?

複雜的Excel文件經常需要多個工作表來組織相關資料。 IronXL通過直觀的方法簡化了多工作表的管理,方便地建立、存取和組織工作表。 您只需幾行程式碼即可打開和管理工作簿工作表

using IronXL;
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");

// Populate Sales sheet
salesSheet["A1"].Value = "Sales Dashboard";
salesSheet["A3"].Value = "Region";
salesSheet["B3"].Value = "Q1 Sales";
salesSheet["C3"].Value = "Q2 Sales";
string[] regions = { "North", "South", "East", "West" };
decimal[] q1Sales = { 250000, 180000, 220000, 195000 };
decimal[] q2Sales = { 275000, 195000, 240000, 210000 };
for (int i = 0; i < regions.Length; i++)
{
    salesSheet[$"A{i + 4}"].Value = regions[i];
    salesSheet[$"B{i + 4}"].Value = q1Sales[i];
    salesSheet[$"C{i + 4}"].Value = q2Sales[i];
}

// Populate Inventory sheet
inventorySheet["A1"].Value = "Inventory Status";
string[] products = { "Widget A", "Widget B", "Widget C" };
int[] stock = { 150, 45, 200 };
int[] reorderPoint = { 100, 50, 75 };
for (int i = 0; i < products.Length; i++)
{
    inventorySheet[$"A{i + 4}"].Value = products[i];
    inventorySheet[$"B{i + 4}"].Value = stock[i];
    inventorySheet[$"C{i + 4}"].Value = reorderPoint[i];
    string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
    inventorySheet[$"D{i + 4}"].Value = status;
    if (status == "REORDER")
        inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}

// Summary sheet with cross-sheet formulas
summarySheet["A1"].Value = "Company Overview";
summarySheet["A4"].Value = "Total Q1 Sales";
summarySheet["B4"].Formula = "=SUM(Sales!B4:B7)";
summarySheet["A5"].Value = "Total Q2 Sales";
summarySheet["B5"].Formula = "=SUM(Sales!C4:C7)";
summarySheet["A6"].Value = "Products Need Reorder";
summarySheet["B6"].Formula = "=COUNTIF(Inventory!D4:D6,\"REORDER\")";

// Apply consistent formatting across all sheets
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
    sheet["A1"].Style.Font.Bold = true;
    sheet["A1"].Style.Font.Height = 14;
}
companyReport.SaveAs("CompanyReport.xlsx");
using IronXL;
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");

// Populate Sales sheet
salesSheet["A1"].Value = "Sales Dashboard";
salesSheet["A3"].Value = "Region";
salesSheet["B3"].Value = "Q1 Sales";
salesSheet["C3"].Value = "Q2 Sales";
string[] regions = { "North", "South", "East", "West" };
decimal[] q1Sales = { 250000, 180000, 220000, 195000 };
decimal[] q2Sales = { 275000, 195000, 240000, 210000 };
for (int i = 0; i < regions.Length; i++)
{
    salesSheet[$"A{i + 4}"].Value = regions[i];
    salesSheet[$"B{i + 4}"].Value = q1Sales[i];
    salesSheet[$"C{i + 4}"].Value = q2Sales[i];
}

// Populate Inventory sheet
inventorySheet["A1"].Value = "Inventory Status";
string[] products = { "Widget A", "Widget B", "Widget C" };
int[] stock = { 150, 45, 200 };
int[] reorderPoint = { 100, 50, 75 };
for (int i = 0; i < products.Length; i++)
{
    inventorySheet[$"A{i + 4}"].Value = products[i];
    inventorySheet[$"B{i + 4}"].Value = stock[i];
    inventorySheet[$"C{i + 4}"].Value = reorderPoint[i];
    string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
    inventorySheet[$"D{i + 4}"].Value = status;
    if (status == "REORDER")
        inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}

// Summary sheet with cross-sheet formulas
summarySheet["A1"].Value = "Company Overview";
summarySheet["A4"].Value = "Total Q1 Sales";
summarySheet["B4"].Formula = "=SUM(Sales!B4:B7)";
summarySheet["A5"].Value = "Total Q2 Sales";
summarySheet["B5"].Formula = "=SUM(Sales!C4:C7)";
summarySheet["A6"].Value = "Products Need Reorder";
summarySheet["B6"].Formula = "=COUNTIF(Inventory!D4:D6,\"REORDER\")";

// Apply consistent formatting across all sheets
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
    sheet["A1"].Style.Font.Bold = true;
    sheet["A1"].Style.Font.Height = 14;
}
companyReport.SaveAs("CompanyReport.xlsx");
Imports IronXL

Dim companyReport As WorkBook = WorkBook.Create()
' Create department sheets
Dim salesSheet As WorkSheet = companyReport.CreateWorkSheet("Sales")
Dim inventorySheet As WorkSheet = companyReport.CreateWorkSheet("Inventory")
Dim summarySheet As WorkSheet = companyReport.CreateWorkSheet("Summary")

' Populate Sales sheet
salesSheet("A1").Value = "Sales Dashboard"
salesSheet("A3").Value = "Region"
salesSheet("B3").Value = "Q1 Sales"
salesSheet("C3").Value = "Q2 Sales"
Dim regions As String() = {"North", "South", "East", "West"}
Dim q1Sales As Decimal() = {250000, 180000, 220000, 195000}
Dim q2Sales As Decimal() = {275000, 195000, 240000, 210000}
For i As Integer = 0 To regions.Length - 1
    salesSheet($"A{i + 4}").Value = regions(i)
    salesSheet($"B{i + 4}").Value = q1Sales(i)
    salesSheet($"C{i + 4}").Value = q2Sales(i)
Next

' Populate Inventory sheet
inventorySheet("A1").Value = "Inventory Status"
Dim products As String() = {"Widget A", "Widget B", "Widget C"}
Dim stock As Integer() = {150, 45, 200}
Dim reorderPoint As Integer() = {100, 50, 75}
For i As Integer = 0 To products.Length - 1
    inventorySheet($"A{i + 4}").Value = products(i)
    inventorySheet($"B{i + 4}").Value = stock(i)
    inventorySheet($"C{i + 4}").Value = reorderPoint(i)
    Dim status As String = If(stock(i) <= reorderPoint(i), "REORDER", "OK")
    inventorySheet($"D{i + 4}").Value = status
    If status = "REORDER" Then
        inventorySheet($"D{i + 4}").Style.Font.Color = "#FF0000"
    End If
Next

' Summary sheet with cross-sheet formulas
summarySheet("A1").Value = "Company Overview"
summarySheet("A4").Value = "Total Q1 Sales"
summarySheet("B4").Formula = "=SUM(Sales!B4:B7)"
summarySheet("A5").Value = "Total Q2 Sales"
summarySheet("B5").Formula = "=SUM(Sales!C4:C7)"
summarySheet("A6").Value = "Products Need Reorder"
summarySheet("B6").Formula = "=COUNTIF(Inventory!D4:D6,""REORDER"")"

' Apply consistent formatting across all sheets
For Each sheet As WorkSheet In companyReport.WorkSheets
    sheet("A1").Style.Font.Bold = True
    sheet("A1").Style.Font.Height = 14
Next

companyReport.SaveAs("CompanyReport.xlsx")
$vbLabelText   $csharpLabel

這個範例建立了一個完整的多工作表報告。 每個工作表都有特定的用途:銷售資料、庫存跟踪和摘要視圖。 摘要表使用跨工作表公式整合關鍵指標。 注意工作表引用語法——"Sales!B4:B7"指的是Sales表上的B4到B7單元格。

庫存表展示條件邏輯,將低庫存項目標記為紅色以便立即關注。 foreach迴圈在所有工作表間應用一致的格式,保持整個工作簿的專業外觀。 工作表名稱作為Excel中的標籤出現,允許使用者輕鬆在不同資料視圖之間导航。

在C#中生成Excel文件的最佳實踐是什麼?

在C#中生成高效的Excel文件需要對記憶體使用、錯誤處理和部署的審慎處理。 這些實踐確保您的應用程式在程式化生成Excel試算表時有效擴展並保持可靠性。

對於大文件來說,記憶體管理變得至關重要。 批處理資料,而不是一次載入整個資料集。 以下模式可預測高流量導出時的記憶體使用:

using IronXL;
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Value";
// Process records in manageable batches
foreach (var batch in GetDataInBatches(rowsPerBatch))
{
    foreach (var record in batch)
    {
        sheet[$"A{currentRow}"].Value = record.Id;
        sheet[$"B{currentRow}"].Value = record.Name;
        sheet[$"C{currentRow}"].Value = record.Value;
        currentRow++;
    }
}
workbook.SaveAs("LargeDataset.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Value";
// Process records in manageable batches
foreach (var batch in GetDataInBatches(rowsPerBatch))
{
    foreach (var record in batch)
    {
        sheet[$"A{currentRow}"].Value = record.Id;
        sheet[$"B{currentRow}"].Value = record.Name;
        sheet[$"C{currentRow}"].Value = record.Value;
        currentRow++;
    }
}
workbook.SaveAs("LargeDataset.xlsx");
Imports IronXL

Dim workbook As WorkBook = WorkBook.Create()
Dim sheet As WorkSheet = workbook.CreateWorkSheet("Data")
Dim rowsPerBatch As Integer = 1000
Dim currentRow As Integer = 2
sheet("A1").Value = "ID"
sheet("B1").Value = "Name"
sheet("C1").Value = "Value"
' Process records in manageable batches
For Each batch In GetDataInBatches(rowsPerBatch)
    For Each record In batch
        sheet($"A{currentRow}").Value = record.Id
        sheet($"B{currentRow}").Value = record.Name
        sheet($"C{currentRow}").Value = record.Value
        currentRow += 1
    Next
Next
workbook.SaveAs("LargeDataset.xlsx")
$vbLabelText   $csharpLabel

對於Web應用程式而言,將Excel文件生成於記憶體中並直接流式傳輸給使用者,而不是將臨時文件寫入磁碟。 始終將生成邏輯包裝在錯誤處理中,以防止崩潰並提供有意義的反饋:

// ASP.NET Core controller action with error handling
IActionResult DownloadExcel()
{
    try
    {
        WorkBook workbook = WorkBook.Create();
        WorkSheet sheet = workbook.CreateWorkSheet("Report");
        sheet["A1"].Value = "Report Data";
        // Populate report data here...
        var stream = new MemoryStream();
        workbook.SaveAs(stream);
        stream.Position = 0;
        return File(stream,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "report.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Excel generation failed: {ex.Message}");
        return StatusCode(500, "Failed to generate Excel file.");
    }
}
// ASP.NET Core controller action with error handling
IActionResult DownloadExcel()
{
    try
    {
        WorkBook workbook = WorkBook.Create();
        WorkSheet sheet = workbook.CreateWorkSheet("Report");
        sheet["A1"].Value = "Report Data";
        // Populate report data here...
        var stream = new MemoryStream();
        workbook.SaveAs(stream);
        stream.Position = 0;
        return File(stream,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "report.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Excel generation failed: {ex.Message}");
        return StatusCode(500, "Failed to generate Excel file.");
    }
}
Imports System
Imports System.IO
Imports Microsoft.AspNetCore.Mvc

Public Class YourController
    Inherits Controller

    Public Function DownloadExcel() As IActionResult
        Try
            Dim workbook As WorkBook = WorkBook.Create()
            Dim sheet As WorkSheet = workbook.CreateWorkSheet("Report")
            sheet("A1").Value = "Report Data"
            ' Populate report data here...
            Dim stream As New MemoryStream()
            workbook.SaveAs(stream)
            stream.Position = 0
            Return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx")
        Catch ex As Exception
            Console.WriteLine($"Excel generation failed: {ex.Message}")
            Return StatusCode(500, "Failed to generate Excel file.")
        End Try
    End Function
End Class
$vbLabelText   $csharpLabel

下表總結了關鍵最佳實踐及其應用時機:

IronXL在C#中的Excel生成最佳實踐
場景 建議的方法 收益
Large datasets (>10,000 rows) 批處理帶分塊寫入 降低記憶體占用
Web應用程式下載 使用MemoryStream而非臨時文件 無磁碟IO,回應更快
生產部署 包含有效的IronXL授權金鑰 生成的文件無水印
貨幣和日期 使用FormatString屬性 在Excel中正確顯示區域設置
動態報告 在SaveAs()之前調用EvaluateAll() 公式顯示計算值

IronXL可在無提升權限的受限環境中工作,使其適合於共享託管和容器化部署。 在您的部署包中包含IronXL授權文件,並確保應用程式具有任何臨時文件操作所需的寫入權限。 如需額外的部署指導,請查閱IronXL功能概述以及完整的API文件

您可以從這裡去哪裡?

IronXL將C#中的Excel文件生成從一個複雜的挑戰轉變為簡單的編碼。 您已經學會了建立工作簿、填充單元格、應用格式、使用公式、導出資料庫資料以及管理多個工作表——全部無需Microsoft Office依賴。 這些技術在針對.NET 10的Windows、Linux和雲平台上始終如一地工作。

要更深入了解,探索IronXL操作指南,以讀取和修改現有的Excel文件,或者存取試用授權頁面開始進行生產。 查看符合您的專案需求和規模的授權選擇

如何使用IronXL在C#中生成Excel文件:圖片11 - 授權

常見問題

如何使用C#生成Excel檔案?

您可以使用IronXL在C#中生成Excel檔案,提供簡單的API來建立Excel檔案,無需安裝Microsoft Office或複雜的COM Interop。

是否需要安裝Microsoft Office才能在C#中使用Excel檔案?

不需要,Microsoft Office不是必需的。IronXL允許您在C#中建立和操作Excel檔案,無需任何Office相依性。

使用IronXL比傳統方法有哪些優勢?

IronXL簡化了生成Excel檔案的過程,消除了Microsoft Office和複雜的COM Interop的需求,提供了一個簡單明瞭的API來建立和操作Excel檔案。

我可以使用IronXL將資料庫整合到Excel檔案中嗎?

是的,IronXL支援進階操作如資料庫整合,允許您有效地將資料導出到Excel檔案中。

使用IronXL可以生成哪些檔案格式?

IronXL允許您建立XLS和XLSX檔案格式,使其在不同的Excel檔案生成需求中都能靈活應用。

IronXL是否支援Excel檔案中的進階格式化?

是的,IronXL支援進階格式化功能,使您能夠自定義Excel檔案的外觀和結構。

是否可以使用IronXL自動化電子表格生成?

是的,IronXL提供了工具和技術,自動化電子表格生成,簡化報告建立和資料導出等過程。

如何在.NET應用程式中使用Excel建立報告?

IronXL提供了一種簡單的方法,直接在.NET應用程式中生成Excel檔案來建立報告,為資料展示提供了一個強大的解決方案。

在C#中使用Excel的基本技術有哪些?

在C#中使用IronXL的基礎技術包括基本的電子表格建立、進階格式化及資料庫整合。

在哪裡可以找到在C#中使用IronXL的文件?

您可以在Iron Software網站上找到在C#中使用IronXL的全面文件,其中包括針對各種使用案例的教程和範例。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話