無需 Office Interop 即可在 C# 中產生 Excel 文件
使用IronXL在 C# 中建立 Excel 檔案,這是一個讓您無需 Microsoft Office 即可建立、格式化及填入 Excel 試算表的程式庫。此工具非常適合用於伺服器環境、Docker 容器以及 CI/CD 管道。
為何要在沒有 Microsoft Office 的情況下生成 Excel 檔案?
為什麼 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 | 封閉式 XML | 非營利組織 |
|---|---|---|---|---|
| 價格 | $749 | $599 | 自由的 | 自由的 |
| 依賴辦公室 | 無 | 無 | 無 | 無 |
| 表現 | 速度提升 40 倍* | 好的 | 緩和 | 慢的 |
| 記憶體使用量 | 小於1GB** | 2-3GB | 1-2GB | 3-5GB |
| Docker 支援 | 原生語言 | 限額 | 基本的 | 基本的 |
| 公式支援 | 165 多種函式 | 100+ | 80歲以上 | 基本的 |
| 商業支持 | 是 | 是 | 無 | 無 |
| 學習曲線 | 簡易 | 緩和 | 緩和 | 陡峭 |
*基於近期效能優化 **用於處理大型 Excel 檔案
IronXL提供了哪些效能優勢?
在無需承擔 COM 互通開銷的情況下,效能顯著提升。 傳統辦公室自動化會為每個操作建立單獨的進程實例,消耗記憶體和 CPU 資源。IronXL在應用程式進程空間內的記憶體中處理所有內容,從而在以程式設計方式產生 Excel 檔案時實現更快的執行速度和更低的資源消耗。 該函式庫已進行重大效能優化,最新更新帶來最高達 40 倍的速度提升,並將記憶體使用量從 19.5 GB 大幅降低至 1 GB 以下。
由於IronXL以單一 NuGet 套件的形式提供,因此部署變得非常簡單。 無需維護任何登錄檔項目、COM 註冊或 Office 服務包。 您的持續整合管道運作順暢,且 Docker 容器保持輕量。 這種簡化的方法使IronXL成為廣受歡迎的選擇,正如各類開發者論壇中所討論的那樣,Professionals 在這些論壇中分享他們在不使用 Interop 的情況下進行 Excel 自動化的經驗。
IronXL 功能概述展示了六個關鍵功能:建立電子表格、儲存並匯出為多種格式、編輯帶有圖表的工作簿、使用公式處理資料、使用密碼保護工作簿以及儲存格操作函數。
IronXL 透過直觀的 API 設計,提供完整的 Excel 操作功能。
如何在我的 C# 專案中安裝 IronXL?
對於 DevOps 工作流程,最佳安裝方法是什麼?
透過 NuGet 套件管理員安裝IronXL只需片刻。 在 Visual Studio 中,以滑鼠右鍵按一下您的項目,然後選擇"管理 NuGet 套件"。搜尋"IronXL.Excel",然後按一下"安裝"。 該軟體包會自動包含在 C# 中產生 Excel 檔案所需的所有相依性。 如需針對您開發環境的詳細安裝指引,請參閱《入門概覽》。
或者,使用軟體包管理器控制台:
Install-Package IronXL.Excel
Install-Package IronXL.Excel
套件管理器控制台顯示 IronXL.Excel 安裝成功,包含 28 個依賴項,其中包括 Microsoft.Extensions 和系統程式庫。
套件管理主控台確認IronXL已成功安裝,且包含所有必要依賴項。
如何將IronXL整合至 CI/CD 管道?
針對在自動化建置流程中處理現代 C# 專案的 .NET CLI 使用者:
dotnet add package IronXL.Excel
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 專屬語法範例的類似功能。 當處理舊版檔案格式或遇到檔案大小問題時,此函式庫能提供完整的解決方案。
輸出
Visual Studio 中的偵錯控制台顯示"IronXL 安裝成功!"訊息
主控台輸出確認IronXL已正確安裝,並已準備好執行 Excel 生成任務。
快速入門:使用 C# 建立 Excel 檔案
使用IronXL建立 Excel 檔案只需幾行程式碼,使其非常適合快速開發與部署的場景。
-
使用NuGet套件管理器安裝https://www.nuget.org/packages/IronXL.Excel
PM > Install-Package 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。 "元資料"屬性可讓您嵌入會顯示於 Excel 檔案屬性中的文件資訊,此功能遵循 Microsoft 的文件屬性標準,並有助於 Enterprise 環境中的檔案管理。 進一步了解工作簿元資料的編輯。
CreateWorkSheet() 方法會新增一個具有指定名稱的新工作表。 Excel 熟悉的儲存格表示法(A1、B1 等)讓設定值變得直覺。IronXL會自動處理資料類型轉換,無需明確轉換即可識別日期、數字和文字。 SaveAs() 方法將整個 Excel 檔案寫入磁碟。 如需更多工作表操作功能,請參閱工作表管理教學指南。
輸出
! 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的靈活單元尋址方式。 對於 Excel 使用者來說,字串表示法("A1")感覺很自然,而數值索引則為循環和動態生成提供了程式控制。 範圍賦值("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 行開始以保留標題。 處理大型資料集時,您可以動態新增列與行,或複製儲存格範圍以提升效率。
輸出
員工資料 Excel 表格,包含 ID、姓名、電子郵件、部門、電話、薪資、入職日期和全職狀態等列,顯示兩張員工記錄。
展示IronXL中多種資料類型與儲存格指派方法的員工資料試算表。
如何套用Professional格式?
製作 Enterprise 級 Excel 檔案需要哪些條件?
專業Excel檔案需要的不只原始資料。 當您使用 C# 生成 Excel 檔案時,IronXL 的樣式 API 會透過格式設定、色彩及視覺層級,將普通的試算表轉化為精緻的商務文件。 此函式庫提供完整的儲存格格式設定選項,可協助建立視覺上吸引人的試算表。
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 檔案的必要條件。 若需進階格式設定,請探索條件格式化功能。
調整列寬可以防止文字被截斷。 AutoSizeColumn() 自動適應內容,而 SetColumnWidth() 提供精確控制。 自動調整列與行大小功能可確保您的資料以最佳方式顯示。 數字格式採用 Excel 的格式代碼——請進一步了解 Excel 數字格式以掌握完整的格式設定選項。
邊框與儲存格對齊可定義資料邊界,從而提升可讀性。 BorderType 枚舉提供了各種樣式:細線、中線、粗線、點線和虛線。 邊框與對齊選項會將標題居中,並將數字右對齊,遵循電子表格的慣例。 交錯的行色(常稱為"條紋行")有助於讀者在龐大的資料集中追蹤資訊。
輸出
專業Excel員工數據,藍色標題、格式化貨幣、日期和簡潔邊框,清晰呈現結構化的員工資訊。
Professional 排版的 Excel 檔案,展示IronXL在 Enterprise 文件上的樣式設定能力。
如何透過程式設計使用 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")
如何排除常見公式問題?
此預算範例說明了公式的實際應用。 Formula 屬性接受以等號開頭的標準 Excel 公式語法。IronXL支援常用函數:SUM、AVERAGE、COUNT、MAX、MIN@. 等等。 公式中的儲存格引用與 Excel 中的完全相同,包括相對引用和絕對引用。 若需進行更複雜的計算,請探索 C# 中的 Excel 聚合函數與 Excel 公式。
當公式計算結果與預期不符時:
-確保語法正確:公式必須以 = 開頭
- 檢查儲存格參照:確認範圍是否正確
-撥打
EvaluateAll():儲存前必須撥打此號碼才能查看結果 - 驗證資料類型:確保數值儲存格中包含數字,而非文字
EvaluateAll() 方法處理所有公式,更新整個工作簿中的計算值。 這樣可以確保公式在 Excel 中開啟時顯示結果。 如果不進行評估,Excel 將顯示公式,直到使用者觸發重新計算。 對於涉及 C# 中 Excel 公式的複雜情境,IronXL 提供全面支援。
輸出
第一季預算Excel表格,包含費用類別、每月數值、計算總額、行銷費用百分比和平均支出公式。
包含動態公式的預算試算表,可自動計算總額與百分比。
如何將資料從資料庫匯出至 Excel?
資料庫匯出至 Excel 的最佳實務有哪些?
實際應用中經常需要將資料庫資料匯出到 Excel 中進行報表和分析。IronXL透過內建的 DataTable 支援簡化了此過程,從 C# 應用程式產生 Excel 檔案時無需手動進行欄位對應。 此函式庫提供多種資料庫整合與 DataGrid 相容的方法。
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")
如何優化大型資料庫匯出作業?
這個全面的範例示範了使用 C# 產生 Excel 檔案的完整資料庫到 Excel 工作流程。 DataTable 模擬資料庫檢索 - 在生產環境中,請使用 Entity Framework、Dapper 或 ADO.NET 將其替換為實際的資料庫查詢。 若需直接整合 SQL,可探索從 SQL 資料庫載入 Excel 檔案,或透過 Excel 更新資料庫記錄。
針對大型資料庫匯出,請考慮:
- 批次處理:分段匯出以管理記憶體
- 非同步操作:在匯出過程中保持使用者介面反應靈敏
- 進度回報:向使用者顯示匯出進度
- 錯誤處理:優雅地處理資料庫超時
程式碼產生一份專業的報告,包含標題、格式化的標題和資料行。 公式列動態計算行總計。 摘要部分利用 Excel 公式計算訂單數量並匯總營收,確保當資料變更時,這些數值會隨之更新。 若要使用 DataSets 而非 DataTables,請參閱匯出資料集資料表指南。
輸出
專業的銷售報告Excel文件,包含訂單數據、計算總額、格式化貨幣、日期和匯總統計信息,顯示5筆訂單,總金額為7,377.20美元。
基於資料庫資料生成的Professional銷售報告,具備自動計算與格式化功能。
需要簡化您的 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 電子表格時能夠有效擴展並保持可靠性。 請參閱Enterprise部署的安全最佳實務與檔案保護選項。
處理大型檔案時,記憶體管理至關重要。 不要將整個資料集載入到記憶體中,而是分塊處理資料:
// 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 Teams 的常見問題有哪些?
| 問題 | 解決方案 | 預防 |
|---|---|---|
| 記憶體不足 | 分批處理 | 監控批次大小 |
| 檔案鎖定 | 使用流,而非檔案 | 實施適當的資源釋放 |
| 授權錯誤 | 在程式碼中驗證授權 | 正確套用授權 |
| 表現 | 啟用非同步操作 | 效能瓶頸 |
| 容器相關問題 | 安裝依賴項 | 在 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
針對網頁應用程式,請在記憶體中生成 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 和雲端平台上都能穩定運作。
如需探索進階功能,請參閱:
- 建立 Excel 圖表以進行視覺化資料呈現
- 添加圖片以強化報告
- 處理互動式文件中的超連結
- Excel PRINT設定,以獲得專業級輸出效果
- 轉換試算表檔案格式以確保最大相容性
準備好在您的 C# 應用程式中實現 Excel 生成功能了嗎? 立即開始免費試用,或瀏覽詳盡的 API 文件以了解進階功能。 若需進行生產環境部署,請查看符合您專案需求的授權選項。 隨著需求增長,建議您考慮探索授權擴展與升級方案。
提供靈活的授權方案,滿足您從開發到Enterprise部署的 Excel 生成需求。
常見問題解答
IronXL 是什麼?
IronXL 是一個函式庫,允許開發人員在 C# 中創建、閱讀和編輯 Excel 文件,而不需 Microsoft Office 或複雜的 COM Interop。
我如何能使用 C# 生成 Excel 文件?
您可以使用 IronXL 在 C# 中生成 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 的常見用例包括創建報表、數據匯出、自動化試算表任務和整合 Excel 功能於 .NET 應用程序內。
IronXL 如何簡化 C# 中的 Excel 文件創建?
IronXL 通過提供簡單而直觀的 API 簡化了 Excel 文件的創建,去除了複雜的設定和依賴,從而簡化了開發過程。


