無需 Office Interop 即可在 C# 中產生 Excel 文件
在C#中使用IronXL程式庫建立Excel文件,這個程式庫允許您製作、格式化和填充Excel試算表而不需使用Microsoft Office。這非常適合伺服器環境、Docker容器和CI/CD管道。
為什麼生成Excel文件不使用Microsoft Office?
為什麼Office-Free Excel生成對於DevOps很重要?
不使用Office開發Excel生成功能可解決關鍵部署挑戰。 伺服器環境通常因為許可費用和資源需求而缺少Microsoft Office。 每個Office安裝需要大量磁碟空間和記憶體,使其不適合雲部署或容器化應用。 當部署到AWS Lambda或運行於Docker容器時,輕量化的解決方案對基礎設施自動化至關重要。
IronXL通過獨立運作消除了這些限制。 您的Excel文件生成能在Windows、Linux、macOS、Docker容器或Azure App Services上運行,無需任何更改。 這種跨平台的相容性意味著您只需編寫一次,便能在任何地方部署,無論是針對.NET Framework、.NET Core或.NET 8/9應用程式。 對於使用.NET MAUI或Blazor的團隊,IronXL在所有現代.NET平台上無縫整合。

IronXL支持所有主要的.NET平台和操作系統,以最大化部署靈活性。
IronXL與其他Excel程式庫相比如何?
| 功能 | IronXL | EPPlus | ClosedXML | NPOI |
|---|---|---|---|---|
| 價格 | $999 | $599 | 免費 | 免費 |
| Office依賴性 | None | None | None | None |
| 性能 | 快40倍* | 良好 | 中等 | 慢 |
| 記憶體使用 | <1GB** | 2-3GB | 1-2GB | 3-5GB |
| Docker支持 | 原生 | 有限 | 基本 | 基本 |
| 公式支持 | 165+函式 | 100+ | 80+ | 基本 |
| 商業支持 | 是 | 是 | 否 | 否 |
| 學習曲線 | 容易 | 中等 | 中等 | 陡峭 |
*基於最近的性能改進 **為處理大型Excel文件
IronXL提供哪些性能優勢?
性能顯著提升,沒有COM Interop的開銷。 傳統的Office自動化為每個操作建立單獨的進程實例,消耗記憶體和CPU資源。 IronXL在您的應用程式的進程空間中以記憶體的方式處理所有內容,從而在程式生成Excel文件時實現更快的執行和更低的資源消耗。 該程式庫經歷了重大性能改進,最近的更新將速度提高至最多40倍,並顯著減少了記憶體使用量,從19.5 GB減少到不到1 GB。
部署變得簡單,因為IronXL作為單一的NuGet包提供。 無需維護註冊表項、COM註冊或Office服務包。 您的持續整合管道運行順利,Docker容器保持輕量化。 這種簡化的方式使IronXL成為受歡迎的選擇,正如在各種開發者論壇中專業人士分享他們的無Interop的Excel自動化經驗中所述。

IronXL通過直覺的API設計提供完整的Excel操作功能。
如何在我的C#專案中安裝IronXL?
什麼是DevOps工作流的最佳安裝方法?
通過NuGet包管理器安裝IronXL只需片刻。 在Visual Studio中,右鍵單擊您的專案並選擇"管理NuGet Packages。" 搜索"IronXL.Excel"並點擊安裝。 該包自動包括所有在C#中生成Excel文件所需的依賴項。 為了獲得與您的開發環境相關的詳細安裝指南,請參考入門概覽。
或者,使用包管理器控制台:
Install-Package IronXL.Excel

包管理器控制台確認IronXL安裝成功,包含所有所需的依賴項。
如何將IronXL整合到CI/CD管道中?
對於使用現代C#專案的.NET CLI使用者來說,在自動化構建管道中:
dotnet add package IronXL.Excel
對於容器化部署,新增到您的Dockerfile中:
RUN dotnet add package IronXL.Excel
使用這個簡單的測試來驗證安裝,以程式方式建立Excel文件:
using IronXL;
// new Excel workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");
using IronXL;
// new Excel workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");
Imports IronXL
' new Excel workbook
Dim workbook = WorkBook.Create()
Console.WriteLine("IronXL installed successfully!")
此程式碼建立一個記憶體中的工作簿物件。 如果無錯誤運行,IronXL已準備好使用。 該程式庫支持所有現代.NET版本,確保與您的現有專案相容。 對於VB.NET開發者,提供類似的功能,請參考VB特定語法範例。 當處理舊版文件格式或遇到文件大小問題時,程式庫提供完整解決方案。
輸出

控制台輸出確認IronXL已正確安裝並準備好進行Excel生成任務。
快速開始:在C#中建立Excel文件
使用IronXL建立Excel文件只需要幾行程式碼,使其非常適合快速開發和部署場景。
-
使用NuGet套件管理器安裝https://www.nuget.org/packages/IronXL.Excel
-
複製並運行這段程式碼片段。
using IronXL; // Create a new workbook WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX); // Add a worksheet WorkSheet sheet = workbook.CreateWorkSheet("Sales"); // Add data sheet["A1"].Value = "Product"; sheet["B1"].Value = "Quantity"; sheet["C1"].Value = "Revenue"; // Save the file workbook.SaveAs("sales_report.xlsx"); -
部署以在您的實時環境中測試
今天就開始在您的專案中使用IronXL,透過免費試用
如何建立我的第一個Excel文件?
基本Excel生成的必要步驟是什麼?
使用IronXL建立Excel文件從WorkBook類開始,這是您進行所有Excel操作的入口。 該程式庫支持現代XLSX和舊版XLS格式,使您在C#中生成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 some basic data
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 some basic data
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 some basic data
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")
應如何在生成的Excel文件中使用元資料?
此程式碼演示了Excel文件生成的幾個關鍵概念。 WorkBook.Create()方法在記憶體中初始化一個新的Excel文件。 您可以使用ExcelFileFormat列舉來指定格式 - 選擇XLSX以符合現代Excel相容性或選擇XLS以支持舊版。 元資料屬性允許您嵌入文件資訊以顯示在Excel的文件屬性中,遵循Microsoft的文件屬性標準,有助於文件在企業環境中的組織。 了解更多關於編輯工作簿元資料的資訊。
CreateWorkSheet()方法按指定名稱新增新工作表。 Excel熟悉的單元格標註法(A1,B1等)使得設置值變得直觀。IronXL自動處理資料型別轉換,無需顯式強制轉換即可識別日期、數字和文字。 SaveAs()方法將完整的Excel文件寫入磁碟。 有關更多工作表操作,請探索工作表管理教程。
輸出

由IronXL生成的基本Excel文件顯示結構化資料和適當的列標題。
如何將資料寫入Excel單元格?
填充Excel資料的有效方法是什麼?
IronXL提供多種方法來填充Excel單元格,從個別單元格分配到批量範圍操作均可應用。 了解這些方法幫助您為您的資料方案選擇最有效的方法。 寫入Excel值指南全面涵蓋所有可用選項。
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Create a worksheet
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
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales"); // C2
worksheet.SetCellValue(2, 2, "Marketing"); // C3
// Array-based 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");
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Create a worksheet
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
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales"); // C2
worksheet.SetCellValue(2, 2, "Marketing"); // C3
// Array-based 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");
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
' Create a worksheet
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
worksheet("B1:B3").Value = "Active"
' Using numeric indices (0-based)
worksheet.SetCellValue(0, 2, "Department") ' C1
worksheet.SetCellValue(1, 2, "Sales") ' C2
worksheet.SetCellValue(2, 2, "Marketing") ' C3
' Array-based 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")
如何有效地處理大資料集?
程式碼展示了IronXL的靈活的單元格索引。 字串標註("A1")對於Excel使用者感覺自然,而數字索引則提供了對迴圈和動態生成的程式化控制。 範圍分配("B1:B3")有效地設置多個單元格為相同的值,適合於初始化列或應用預設值。 在命名範圍或命名表工作時,IronXL提供了更多的組織能力。
對於較大的資料集,考慮使用以下方式:
// Populate from a data source
var employees = GetEmployeeData(); // Your data source
for (int row = 0; row < employees.Count; row++)
{
worksheet[$"A{row + 2}"].Value = employees[row].Id;
worksheet[$"B{row + 2}"].Value = employees[row].Name;
worksheet[$"C{row + 2}"].Value = employees[row].Department;
worksheet[$"D{row + 2}"].Value = employees[row].Salary;
}
// Populate from a data source
var employees = GetEmployeeData(); // Your data source
for (int row = 0; row < employees.Count; row++)
{
worksheet[$"A{row + 2}"].Value = employees[row].Id;
worksheet[$"B{row + 2}"].Value = employees[row].Name;
worksheet[$"C{row + 2}"].Value = employees[row].Department;
worksheet[$"D{row + 2}"].Value = employees[row].Salary;
}
' Populate from a data source
Dim employees = GetEmployeeData() ' Your data source
For row As Integer = 0 To employees.Count - 1
worksheet($"A{row + 2}").Value = employees(row).Id
worksheet($"B{row + 2}").Value = employees(row).Name
worksheet($"C{row + 2}").Value = employees(row).Department
worksheet($"D{row + 2}").Value = employees(row).Salary
Next
此方法遍歷您的資料集合,將每個屬性映射到其相應的列。 字串插值($"A{row + 2}")動態生成單元格地址,從第2行開始以保留標題。 在處理大資料集時,您可以動態新增行和列或複製單元格範圍以提高效率。
輸出

員工資料試算表演示了IronXL中的多種資料型別和單元格分配方法。
如何應用專業格式化?
建立企業級Excel文件需要什麼?
專業的Excel文件不僅僅是原始資料。 IronXL的樣式API通過格式、顏色和視覺層次將簡單的試算表轉變為打磨過的商業文件,當您在C#中生成Excel文件時。 該程式庫提供完整的單元格格式選項以建立視覺上吸引人的試算表。
using IronXL;
using IronXL.Formatting;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Create a worksheet
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Add sample data first
worksheet["A1"].Value = "ID";
worksheet["B1"].Value = "Name";
worksheet["C1"].Value = "Department";
worksheet["D1"].Value = "Phone";
worksheet["E1"].Value = "Salary";
worksheet["F1"].Value = "Start Date";
worksheet["G1"].Value = "Full Time";
// Add employee data
worksheet["A2"].Value = 101;
worksheet["B2"].Value = "John Smith";
worksheet["C2"].Value = "Sales";
worksheet["D2"].Value = "(555) 123-4567";
worksheet["E2"].Value = 75000.50m;
worksheet["F2"].Value = new DateTime(2020, 3, 15);
worksheet["G2"].Value = true;
worksheet["A3"].Value = 102;
worksheet["B3"].Value = "Jane Doe";
worksheet["C3"].Value = "Marketing";
worksheet["D3"].Value = "(555) 987-6543";
worksheet["E3"].Value = 82000.75m;
worksheet["F3"].Value = new DateTime(2019, 7, 1);
worksheet["G3"].Value = true;
// Header formatting
var headerRange = worksheet["A1:G1"];
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.SetColumnWidth(1, 20); // Set column B to 20 characters
// 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;
// To set border color, use:
dataRange.Style.TopBorder.SetColor("#000000");
dataRange.Style.BottomBorder.SetColor("#000000");
dataRange.Style.LeftBorder.SetColor("#000000");
dataRange.Style.RightBorder.SetColor("#000000");
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability
for (int row = 2; row <= 3; row++)
{
if (row % 2 == 0)
{
worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
}
}
workbook.SaveAs("FormattedEmployees.xlsx");
using IronXL;
using IronXL.Formatting;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Create a worksheet
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Add sample data first
worksheet["A1"].Value = "ID";
worksheet["B1"].Value = "Name";
worksheet["C1"].Value = "Department";
worksheet["D1"].Value = "Phone";
worksheet["E1"].Value = "Salary";
worksheet["F1"].Value = "Start Date";
worksheet["G1"].Value = "Full Time";
// Add employee data
worksheet["A2"].Value = 101;
worksheet["B2"].Value = "John Smith";
worksheet["C2"].Value = "Sales";
worksheet["D2"].Value = "(555) 123-4567";
worksheet["E2"].Value = 75000.50m;
worksheet["F2"].Value = new DateTime(2020, 3, 15);
worksheet["G2"].Value = true;
worksheet["A3"].Value = 102;
worksheet["B3"].Value = "Jane Doe";
worksheet["C3"].Value = "Marketing";
worksheet["D3"].Value = "(555) 987-6543";
worksheet["E3"].Value = 82000.75m;
worksheet["F3"].Value = new DateTime(2019, 7, 1);
worksheet["G3"].Value = true;
// Header formatting
var headerRange = worksheet["A1:G1"];
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.SetColumnWidth(1, 20); // Set column B to 20 characters
// 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;
// To set border color, use:
dataRange.Style.TopBorder.SetColor("#000000");
dataRange.Style.BottomBorder.SetColor("#000000");
dataRange.Style.LeftBorder.SetColor("#000000");
dataRange.Style.RightBorder.SetColor("#000000");
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability
for (int row = 2; row <= 3; row++)
{
if (row % 2 == 0)
{
worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
}
}
workbook.SaveAs("FormattedEmployees.xlsx");
Imports IronXL
Imports IronXL.Formatting
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
' Create a worksheet
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("Employees")
' Add sample data first
worksheet("A1").Value = "ID"
worksheet("B1").Value = "Name"
worksheet("C1").Value = "Department"
worksheet("D1").Value = "Phone"
worksheet("E1").Value = "Salary"
worksheet("F1").Value = "Start Date"
worksheet("G1").Value = "Full Time"
' Add employee data
worksheet("A2").Value = 101
worksheet("B2").Value = "John Smith"
worksheet("C2").Value = "Sales"
worksheet("D2").Value = "(555) 123-4567"
worksheet("E2").Value = 75000.5D
worksheet("F2").Value = New DateTime(2020, 3, 15)
worksheet("G2").Value = True
worksheet("A3").Value = 102
worksheet("B3").Value = "Jane Doe"
worksheet("C3").Value = "Marketing"
worksheet("D3").Value = "(555) 987-6543"
worksheet("E3").Value = 82000.75D
worksheet("F3").Value = New DateTime(2019, 7, 1)
worksheet("G3").Value = True
' Header formatting
Dim headerRange = worksheet("A1:G1")
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.SetColumnWidth(1, 20) ' Set column B to 20 characters
' 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
' To set border color, use:
dataRange.Style.TopBorder.SetColor("#000000")
dataRange.Style.BottomBorder.SetColor("#000000")
dataRange.Style.LeftBorder.SetColor("#000000")
dataRange.Style.RightBorder.SetColor("#000000")
' Text alignment
worksheet("A1:G1").Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center
' Alternating row colors for readability
For row As Integer = 2 To 3
If row Mod 2 = 0 Then
worksheet($"A{row}:G{row}").Style.SetBackgroundColor("#F2F2F2")
End If
Next row
workbook.SaveAs("FormattedEmployees.xlsx")
如何實施高級的樣式功能?
這段格式化程式碼建立一個符合企業標準的專業外觀。 帶有背景圖案和顏色的粗體標題建立了視覺層次。 SetBackgroundColor()方法接受十六進位顏色程式碼,為您的配色方案提供精確控制。 字體屬性包括大小、顏色、粗體、斜體和下畫線選項,這些都是建立符合企業品牌指南的Excel文件的必要條件。 如需高級樣式需求,探索條件格式化功能。
列寬調整可防止文字截斷。 SetColumnWidth()則提供精確控制。 自動調整行和列功能確保您的資料顯示最佳效果。 數字格式化使用Excel的格式程式碼 - 瞭解更多關於Excel數字格式的全面格式化選項。
邊框和單元格對齊定義資料邊界,提高可讀性。 BorderType枚舉提供多種樣式:細,中,厚,點和虛線。 邊框和對齊選項中心標題和右對齊數字,遵循試算表約定。 交替行顏色,通常稱爲"帶狀行",幫助讀者在廣泛的資料集中跟蹤資訊。
輸出

由IronXL生成的專業格式化Excel文件,展示了用於企業文件的風格能力。
我如何以編程方式使用Excel公式?
哪些公式功能可實現動態計算?
Excel公式通過自動計算賦予試算表活力。 IronXL支持公式的建立和評估,實現動態的試算表,自動更新。 該庫包括對165多種Excel函式的支持,允許您以程式方式編輯公式。
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
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];
// Row total formula
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";
budget["C9"].Formula = "=C3/C7*100";
budget["D9"].Formula = "=D3/D7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");
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
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];
// Row total formula
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";
budget["C9"].Formula = "=C3/C7*100";
budget["D9"].Formula = "=D3/D7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");
Imports System
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
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)
' Row total formula
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"
budget("C9").Formula = "=C3/C7*100"
budget("D9").Formula = "=D3/D7*100"
' Average calculation
budget("A10").Value = "Average Spending"
budget("B10").Formula = "=AVERAGE(B2:B6)"
' Evaluate all formulas
workbook.EvaluateAll()
workbook.SaveAs("Budget.xlsx")
我如何排查常見的公式問題?
這個預算範例說明了實際的公式應用。 公式屬性接受標準的Excel公式語法,以等號開頭。 IronXL支持常見函式:MIN以及其他許多。 公式中的單元格引用工作與Excel中完全一樣,包括相對和絕對引用。 對於更高級的計算,探索聚合Excel函式和C#中的Excel公式。
當公式未按預期計算時:
- 確保正確語法:公式必須以
=開頭 - 檢查單元格引用:驗證範圍是否正確
- 调用
EvaluateAll():保存前需調用以查看結果 - 驗證資料型別:確保數字單元格包含數字而非文字
EvaluateAll()方法處理所有公式,在整個工作簿中更新計算值。 這確保了公式在Excel中打開時顯示結果。 如果不評估,Excel將顯示公式直到使用者觸發重新計算。 對於涉及複雜場景的C#中的Excel公式,IronXL提供了全面支持。
輸出

預算工作表具有活動公式自動計算總數和百分比。
我如何從資料庫導出資料到Excel?
資料庫到Excel導出的最佳實踐是什麼?
現實應用程式常常將資料庫資料導出到Excel以進行報告和分析。 IronXL通過內建的DataTable支持簡化了這一過程,在從C#應用生成Excel文件時消除了手動字段映射。 該庫提供多種方法用於資料庫整合和資料網格相容性。
using System.Data;
using System.Data.SqlClient;
// Simulate database retrieval (replace with your 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));
// Sample data (normally from database)
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");
// Get data from database
DataTable salesData = GetSalesData();
// Method 1: Manual mapping with formatting
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);
}
// Format headers
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]);
}
// Add total column with formula
reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}
// Add total header and format
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency 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";
// Format date column
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";
// Add 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";
// Auto-fit columns
for (int col = 0; col <= 6; col++)
{
reportSheet.AutoSizeColumn(col);
}
// Evaluate formulas and save
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");
using System.Data;
using System.Data.SqlClient;
// Simulate database retrieval (replace with your 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));
// Sample data (normally from database)
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");
// Get data from database
DataTable salesData = GetSalesData();
// Method 1: Manual mapping with formatting
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);
}
// Format headers
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]);
}
// Add total column with formula
reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}
// Add total header and format
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency 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";
// Format date column
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";
// Add 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";
// Auto-fit columns
for (int col = 0; col <= 6; col++)
{
reportSheet.AutoSizeColumn(col);
}
// Evaluate formulas and save
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");
Imports System.Data
Imports System.Data.SqlClient
' Simulate database retrieval (replace with your 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))
' Sample data (normally from database)
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")
' Get data from database
Dim salesData As DataTable = GetSalesData()
' Method 1: Manual mapping with formatting
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
' Format headers
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
' Add total column with formula
reportSheet($"G{row + headerRow + 1}").Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}"
Next
' Add total header and format
reportSheet("G3").Value = "Total"
reportSheet("G3").Style.Font.Bold = True
reportSheet("G3").Style.SetBackgroundColor("#D9E1F2")
' Format currency 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"
' Format date column
reportSheet($"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}").FormatString = "MM/dd/yyyy"
' Add 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"
' Auto-fit columns
For col As Integer = 0 To 6
reportSheet.AutoSizeColumn(col)
Next
' Evaluate formulas and save
reportWorkbook.EvaluateAll()
reportWorkbook.SaveAs("DatabaseExport.xlsx")
我如何優化大型資料庫導出?
這個全面的範例展示了一個完整的資料庫到Excel的工作流,用於在C#中生成Excel文件。 DataTable模擬資料庫檢索-在生產中,用您的實際資料庫查詢替換此內容,使用Entity Framework、Dapper或ADO.NET。 對直接的SQL整合,探索從SQL資料庫載入Excel文件或從Excel更新資料庫記錄。
對於大型資料庫導出,考慮:
- 批处理:分块导出来管理内存
- 異步操作:導出過程中保持UI響應
- 進度報告:向使用者顯示導出進度
- 錯誤處理:優雅地處理資料庫超時
程式碼生成了一個帶有標題、格式化標題和資料行的專業報告。 公式列可動態計算行總數。 摘要部分使用Excel公式計算訂單數量和總收入,確保這些值在資料更改時更新。 對於處理DataTables的情況,請查看導出資料集資料表指南。
輸出

從資料庫資料生成的專業銷售報告,具有自動計算和格式化。
需要簡化您的Excel報告嗎? 購買授權以解鎖IronXL的全部潛力,用於生產部署。
如何處理多個工作表?
什麼時候應使用多工作表工作簿?
複雜的Excel文件通常需要多個工作表來組織相關資料。 IronXL透過直觀的方法簡化多工作表管理,用於建立、存取和組織工作表。 了解更多關於管理工作表和複製工作表資料以應對高級場景。
// Create a multi-sheet workbook
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet hrSheet = companyReport.CreateWorkSheet("HR Metrics");
// 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";
inventorySheet["A3"].Value = "Product";
inventorySheet["B3"].Value = "Stock Level";
inventorySheet["C3"].Value = "Reorder Point";
inventorySheet["D3"].Value = "Status";
// Add inventory data with conditional 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];
// Status based on stock level
string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
inventorySheet[$"D{i + 4}"].Value = status;
// Color code status
if (status == "REORDER")
{
inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}
}
// Create summary sheet referencing other sheets
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");
summarySheet["A1"].Value = "Company Overview";
summarySheet["A3"].Value = "Metric";
summarySheet["B3"].Value = "Value";
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\")";
// Format all sheets consistently
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
// Format headers
sheet["A1"].Style.Font.Bold = true;
sheet["A1"].Style.Font.Height = 14;
var headerRow = sheet["A3:D3"];
headerRow.Style.Font.Bold = true;
headerRow.Style.SetBackgroundColor("#E7E6E6");
}
// Save multi-sheet workbook
companyReport.SaveAs("CompanyReport.xlsx");
// Create a multi-sheet workbook
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet hrSheet = companyReport.CreateWorkSheet("HR Metrics");
// 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";
inventorySheet["A3"].Value = "Product";
inventorySheet["B3"].Value = "Stock Level";
inventorySheet["C3"].Value = "Reorder Point";
inventorySheet["D3"].Value = "Status";
// Add inventory data with conditional 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];
// Status based on stock level
string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
inventorySheet[$"D{i + 4}"].Value = status;
// Color code status
if (status == "REORDER")
{
inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}
}
// Create summary sheet referencing other sheets
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");
summarySheet["A1"].Value = "Company Overview";
summarySheet["A3"].Value = "Metric";
summarySheet["B3"].Value = "Value";
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\")";
// Format all sheets consistently
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
// Format headers
sheet["A1"].Style.Font.Bold = true;
sheet["A1"].Style.Font.Height = 14;
var headerRow = sheet["A3:D3"];
headerRow.Style.Font.Bold = true;
headerRow.Style.SetBackgroundColor("#E7E6E6");
}
// Save multi-sheet workbook
companyReport.SaveAs("CompanyReport.xlsx");
Imports System
' Create a multi-sheet workbook
Dim companyReport As WorkBook = WorkBook.Create()
' Create department sheets
Dim salesSheet As WorkSheet = companyReport.CreateWorkSheet("Sales")
Dim inventorySheet As WorkSheet = companyReport.CreateWorkSheet("Inventory")
Dim hrSheet As WorkSheet = companyReport.CreateWorkSheet("HR Metrics")
' 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() = {250000D, 180000D, 220000D, 195000D}
Dim q2Sales As Decimal() = {275000D, 195000D, 240000D, 210000D}
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"
inventorySheet("A3").Value = "Product"
inventorySheet("B3").Value = "Stock Level"
inventorySheet("C3").Value = "Reorder Point"
inventorySheet("D3").Value = "Status"
' Add inventory data with conditional 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)
' Status based on stock level
Dim status As String = If(stock(i) <= reorderPoint(i), "REORDER", "OK")
inventorySheet($"D{i + 4}").Value = status
' Color code status
If status = "REORDER" Then
inventorySheet($"D{i + 4}").Style.Font.Color = "#FF0000"
End If
Next
' Create summary sheet referencing other sheets
Dim summarySheet As WorkSheet = companyReport.CreateWorkSheet("Summary")
summarySheet("A1").Value = "Company Overview"
summarySheet("A3").Value = "Metric"
summarySheet("B3").Value = "Value"
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"")"
' Format all sheets consistently
For Each sheet As WorkSheet In companyReport.WorkSheets
' Format headers
sheet("A1").Style.Font.Bold = True
sheet("A1").Style.Font.Height = 14
Dim headerRow = sheet("A3:D3")
headerRow.Style.Font.Bold = True
headerRow.Style.SetBackgroundColor("#E7E6E6")
Next
' Save multi-sheet workbook
companyReport.SaveAs("CompanyReport.xlsx")
如何在多個工作表之間引用資料?
這個範例建立了一個完整的多工作表報告。 每個工作表都有特定用途:銷售資料、庫存追蹤和人力資源統計。 摘要工作表使用跨工作表公式匯總關鍵指標。 注意公式中的工作表引用語法 - "Sales!B4:B7"指的是銷售工作表上的B4至B7單元格。 對於更複雜的操作,探索合併Excel範圍和組合和解組行和列。
庫存工作表示範了條件邏輯,即將庫存不足的項目用紅色標示以引起注意。 foreach迴圈在所有工作表上應用一致的格式,使整個工作簿保持專業的外觀。 工作表名稱作為Excel中的標籤出現,使使用者可以輕鬆地在不同的資料視圖之間切換。 對於高級場景,考慮新增凍結窗格,以便在瀏覽大資料集時保持標題可見。
Excel生成的最佳實踐是什麼?
如何確保生產環境中的大規模Excel生成?
在C#中有效地生成Excel文件需要對記憶體使用、錯誤處理和部署的深思熟慮的方法。 這些做法可確保你的應用在程式生成Excel試算表時有效擴展,同時保持可靠性。 查看安全最佳實踐和企業部署的文件保護選項。
對於大文件,記憶體管理變得至關重要。 而不是將整個資料集載入到記憶體中,分塊處理資料:
// Process large datasets efficiently
public void ExportLargeDataset(string filename)
{
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 1;
// Process in 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(filename);
}
// Process large datasets efficiently
public void ExportLargeDataset(string filename)
{
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 1;
// Process in 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(filename);
}
' Process large datasets efficiently
Public Sub ExportLargeDataset(filename As String)
Dim workbook As WorkBook = WorkBook.Create()
Dim sheet As WorkSheet = workbook.CreateWorkSheet("Data")
Dim rowsPerBatch As Integer = 1000
Dim currentRow As Integer = 1
' Process in 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(filename)
End Sub
DevOps團隊常見的問題是什麼?
| 問題 | 解決方案 | 預防措施 |
|---|---|---|
| 記憶體溢出 | 分批處理 | 監控批量大小 |
| 文件鎖定 | 使用流而非文件 | 實施適當的回收 |
| 授權錯誤 | 在程式碼中驗證授權 | 正確應用授權 |
| 性能 | 啟用異步操作 | 配置瓶頸 |
| 容器問題 | 安裝依賴項 | 在本地Docker中測試 |
錯誤處理可防止應用程式崩潰,並在生成Excel文件時提供有意義的反饋:
try
{
WorkBook workbook = WorkBook.Create();
// Excel generation code
workbook.SaveAs("output.xlsx");
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Excel generation failed: {ex.Message}");
// Implement appropriate recovery or notification
}
try
{
WorkBook workbook = WorkBook.Create();
// Excel generation code
workbook.SaveAs("output.xlsx");
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Excel generation failed: {ex.Message}");
// Implement appropriate recovery or notification
}
Imports System
Try
Dim workbook As WorkBook = WorkBook.Create()
' Excel generation code
workbook.SaveAs("output.xlsx")
Catch ex As Exception
' Log the error
Console.WriteLine($"Excel generation failed: {ex.Message}")
' Implement appropriate recovery or notification
End Try
對於Web應用程式,在記憶體中生成Excel文件並流式傳輸給使用者。 此方法與ASP.NET MVC應用程式完美配合:
// ASP.NET Core example
public IActionResult DownloadExcel()
{
WorkBook workbook = GenerateReport();
var stream = new MemoryStream();
workbook.SaveAs(stream);
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx");
}
// ASP.NET Core example
public IActionResult DownloadExcel()
{
WorkBook workbook = GenerateReport();
var stream = new MemoryStream();
workbook.SaveAs(stream);
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx");
}
Imports System.IO
Imports Microsoft.AspNetCore.Mvc
Public Function DownloadExcel() As IActionResult
Dim workbook As WorkBook = GenerateReport()
Dim stream As New MemoryStream()
workbook.SaveAs(stream)
stream.Position = 0
Return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx")
End Function
如何配置IronXL以方便容器部署?
部署考量可確保順利的生產操作。 IronXL在無需提升權限的受限環境中運行,使其適用於共享託管和容器化部署。 將IronXL授權文件包含在部署包中,並確保應用程式具有寫權限,以供需要時進行臨時文件操作。 對於適當的授權配置,請參閱使用授權密碼和web.config設定。
對於Docker部署:
FROM mcr.microsoft.com/dotnet/runtime:8.0
WORKDIR /app
COPY . .
#安裝依賴項for Excel operations
RUN apt-get update && apt-get install -y libgdiplus
ENV IRONXL_LICENSE_KEY=${IRONXL_LICENSE_KEY}
ENTRYPOINT ["dotnet", "YourApp.dll"]
在處理敏感資料時,請考慮密碼保護工作簿和保護工作表。 IronXL提供全面的安全功能,以保護您的Excel文件免於未經授權的存取。 為了處理大文件的最佳性能,實施資料修剪和清除單元格策略,以有效管理文件大小。
對於Linux部署,根據Linux安裝指南,確保正確配置。 在部署到AWS Lambda時,請參考AWS部署指南以獲取適用於無伺服器的配置。
本指南後的下一步是什麼?
IronXL將C#中的Excel文件生成從複雜的挑戰轉化為簡單的編碼。 您已學會建立工作簿、填充單元格、應用格式、使用公式及導出資料庫資料—所有這些均無需依賴Microsoft Office。 這些用于程式生成Excel文件的技術在Windows、Linux和雲平台上一致地工作。
如需高級功能,探索:
準備好在您的C#應用程式中實現Excel生成嗎? 開始您的免費試用或探索全面的API文件以獲取高級功能。 對於生產部署,請查看授權選項以符合您的專案要求。 隨著您的需求增長,請考慮探索授權擴展和升級路徑。

靈活的授權選項,以滿足您從開發到企業部署的Excel生成需求。
常見問題
什麼是IronXL?
IronXL是一個程式庫,它允許開發人員在C#中建立、讀取和編輯Excel文件,而不需要Microsoft Office或複雜的COM Interop。
如何使用C#生成Excel文件?
您可以使用IronXL生成Excel文件,IronXL提供了一個簡單的API來程式地建立、格式化和操縱Excel文件。
我需要安裝Microsoft Office來使用IronXL嗎?
不,IronXL不需要在您的系統上安裝Microsoft Office,這使它成為建立和編輯Excel文件的輕便解決方案。
IronXL可以處理高級Excel格式化嗎?
可以,IronXL支持高級格式選項,讓您能夠將樣式、格式和其他Excel功能應用至您的試算表。
是否可以使用IronXL將Excel文件與資料庫整合?
是的,IronXL使您能夠將Excel文件與資料庫整合,便於直接從C#應用程式進行資料導出和報告。
IronXL可以處理哪些文件格式?
IronXL可以處理XLS和XLSX兩種文件格式,提供靈活性以處理Excel文件。
我可以用IronXL自動化試算表生成嗎?
可以,IronXL允許您自動化生成試算表,非常適合用於報告建立和資料導出等任務。
IronXL支持.NET應用程式嗎?
IronXL完全相容.NET應用程式,允許在您的C#專案中無縫整合和功能運作。
IronXL的一些常見使用案例是什麼?
IronXL的常見使用案例包括建立報告、導出資料、自動化試算表任務以及在.NET應用程式中整合Excel功能。
IronXL如何簡化C#中的Excel文件建立?
IronXL通過提供一個簡單直觀的API來簡化Excel文件建立,消除了複雜的設置和依賴,從而簡化了開發過程。




