跳至頁尾內容
使用 IRONXL

無需 Office Interop 即可在 C# 中產生 Excel 文件

使用 IronXL 庫,無需 Microsoft Office 即可在 C# 中建立 Excel 文件,該庫可讓您建立、格式化和填入 Excel 電子表格。這非常適合伺服器環境、Docker 容器和 CI/CD 管線。

為什麼要在不使用 Microsoft Office 的情況下產生 Excel 檔案?

為什麼免 Office Excel 產生對DevOps很重要?

無需 Office 即可開發 Excel 生成功能,從而解決關鍵的部署難題。 由於授權成本和資源需求,伺服器環境通常缺乏 Microsoft Office。 每個 Office 安裝都需要大量的磁碟空間和內存,因此不適合雲端部署或容器化應用程式。 當部署到 AWS Lambda 或在 Docker 容器中運行時,輕量級解決方案對於基礎設施自動化至關重要。

IronXL 透過獨立運行來克服這些限制。 您的 Excel 檔案產生功能無需任何變更即可在 Windows、Linux、macOS、Docker 容器或 Azure 應用程式服務上執行。 這種跨平台相容性意味著您只需編寫一次程式碼,即可部署到任何地方,無論是面向 .NET Framework、.NET Core 或 .NET 8/9 應用程式。 對於使用.NET MAUIBlazor 的團隊,IronXL 可以無縫整合到所有現代 .NET 平台中。

跨平台 .NET 相容性圖表,展示了對 C#、F# 和 VB.NET 在各種 .NET 版本(6-9、Core、Standard、Framework)上的支持,以及在 Windows、Linux、Mac、Docker、Azure 和 AWS 上的部署選項。

IronXL 支援所有主流 .NET 平台和作業系統,以實現最大的部署靈活性。

IronXL 與其他 Excel 庫相比如何?

特徵IronXLEPPlus封閉式 XML非營利組織
價格$749$599自由的自由的
辦公依賴性沒有任何沒有任何沒有任何沒有任何
表現速度提升40倍*好的緩和慢的
記憶體使用情況小於1GB**2-3GB1-2GB3-5GB
Docker 支援本國的有限的基本的基本的
配方支持165+ 功能100+80歲以上基本的
商業支持是的是的
學習曲線簡單的緩和緩和

*基於近期性能改進 **用於處理大型 Excel 文件

IronXL能帶來哪些性能提升?

無需 COM 互通開銷,效能顯著提升。 傳統辦公室自動化會為每個操作建立單獨的進程實例,消耗記憶體和 CPU 資源。 IronXL 在應用程式進程空間內的記憶體中處理所有內容,從而在以程式設計方式產生 Excel 檔案時實現更快的執行速度和更低的資源消耗。 該庫的性能得到了顯著提升,最近的更新帶來了高達 40 倍的速度提升,並將記憶體使用量從 19.5 GB 大幅降低到 1 GB 以下。

由於 IronXL 以單一 NuGet 套件的形式提供,因此部署變得非常簡單。 無需維護登錄機碼、COM 註冊或 Office 服務包。 您的持續整合管道運作流暢,Docker 容器保持輕量級。 這種簡化的方法使 IronXL 成為一種流行的選擇,正如在各種開發者論壇上討論的那樣,專業人士在論壇上分享了他們在不使用 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
SHELL

套件管理器控制台顯示 IronXL.Excel 安裝成功,包含 28 個依賴項,其中包括 Microsoft.Extensions 和系統程式庫。

軟體套件管理器控制台確認 IronXL 已成功安裝,所有必要的相依性均已安裝。

如何將 IronXL 與 CI/CD 管線整合?

對於在自動化建置管道中使用現代 C# 專案的 .NET CLI 使用者:

dotnet add package IronXL.Excel
dotnet add package IronXL.Excel
SHELL

對於容器化部署,請將其新增至您的 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!");
$vbLabelText   $csharpLabel

這段程式碼會建立一個記憶體中的工作簿物件。 如果運行沒有錯誤,IronXL 即可使用。 該程式庫支援所有現代 .NET 版本,確保與您現有專案的兼容性。 對於 VB.NET 開發人員,可以使用VB 特有的語法範例來實現類似的功能。 當處理舊文件格式或遇到文件大小問題時,該庫提供了完整的解決方案

輸出

Visual Studio 中的偵錯控制台顯示"IronXL 安裝成功!"訊息

控制台輸出確認 IronXL 已正確安裝並準備好執行 Excel 產生任務。

快速入門:使用 C# 建立 Excel 文件

使用 IronXL 建立 Excel 檔案只需要幾行程式碼,非常適合快速開發和部署場景。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronXL

    PM > Install-Package IronXL.Excel

  2. 複製並運行這段程式碼。

    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");
  3. 部署到您的生產環境進行測試

    立即開始在您的專案中使用 IronXL,免費試用!
    arrow pointer

如何建立我的第一個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");
$vbLabelText   $csharpLabel

如何在產生的Excel檔案中使用元資料?

這段程式碼示範了Excel檔案產生的幾個關鍵概念。 WorkBook.Create()方法在記憶體中初始化一個新的 Excel 檔案。 您可以使用ExcelFileFormat列舉指定格式 - 選擇 XLSX 相容於現代 Excel,選擇 XLS 支援舊版 Excel。 元資料屬性可讓您嵌入文件訊息,這些資訊將顯示在 Excel 的文件屬性中,遵循 Microsoft 的文件屬性標準,並有助於在企業環境中進行文件組織。 了解更多關於編輯工作簿元資料的資訊

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");
$vbLabelText   $csharpLabel

如何高效處理大型資料集?

該程式碼展示了 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;
}
$vbLabelText   $csharpLabel

這種方法會遍歷你的資料集合,將每個屬性對應到其對應的列。 字串插值($"A{row + 2}") 動態產生儲存格位址,從第 2 行開始以保留標題。 處理大型資料集時,為了提高效率,可以動態新增行和列,或複製儲存格區域

輸出

員工資料 Excel 表格,包含 ID、姓名、電子郵件、部門、電話、薪資、入職日期和全職狀態等列,顯示兩張員工記錄

員工資料電子表格示範了 IronXL 中的多種資料類型和儲存格分配方法。

如何應用專業格式?

建立企業級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");
$vbLabelText   $csharpLabel

如何實現高階樣式功能?

這種格式化程式碼可以創造符合企業標準的專業外觀。 醒目的標題搭配背景圖案和顏色,可以建立視覺層次感。 SetBackgroundColor()方法接受十六進位顏色程式碼,讓您可以精確控製配色方案。 字體屬性包括大小、顏色、粗體、斜體和底線選項,這些都是建立符合公司品牌指南的 Excel 檔案所必需的。 如需更進階的樣式設置,請探索條件格式功能。

調整列寬可以防止文字被截斷。 AutoSizeColumn()可自動調整內容大小,而SetColumnWidth()可提供精確控制。 自動調整行和列大小的功能可確保您的資料以最佳方式顯示。 數位格式設定使用 Excel 的格式代碼 - 了解更多關於Excel 數字格式的信息,以獲得更全面的格式設定選項。

邊界和單元格對齊方式定義了資料邊界,提高了可讀性。 BorderType枚舉提供了多種樣式:細邊框、中等邊框、粗邊框、點狀邊框和虛線邊框。 邊框和對齊選項使標題居中,數字右對齊,遵循電子表格約定。 交替的行顏色(通常稱為"帶狀行")有助於讀者追蹤大型資料集中的資訊。

輸出

專業Excel員工數據,藍色標題、格式化貨幣、日期和簡潔邊框,清晰呈現結構化的員工資訊

一份專業格式的 Excel 文件,展示了 IronXL 對企業文件的樣式設定功能。

如何以程式設計方式使用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");
$vbLabelText   $csharpLabel

如何排除常見的配方問題?

這個預算範例說明了公式的實際應用。 Formula 屬性接受以等號開頭的標準 Excel 公式語法。 IronXL 支援常用函數: SUMAVERAGECOUNTMAXMIN等。 公式中的儲存格引用與 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");
$vbLabelText   $csharpLabel

如何優化大型資料庫匯出?

這個全面的範例示範了使用 C# 產生 Excel 檔案的完整資料庫到 Excel 工作流程。 DataTable模擬資料庫擷取 - 在生產環境中,請使用 Entity Framework、Dapper 或 ADO.NET 將其替換為實際的資料庫查詢。 對於直接 SQL 集成,可以探索從 SQL 資料庫載入 Excel從 Excel 更新資料庫記錄

對於大型資料庫匯出,請考慮: -批次處理:分塊匯出以管理記憶體 -非同步操作:匯出過程中保持 UI 回應 -進度報告:向使用者顯示匯出進度 -錯誤處理:優雅地處理資料庫逾時

程式碼產生一份專業的報告,包含標題、格式化的標題和資料行。 公式列動態計算行總計。 摘要部分利用 Excel 公式來統計訂單數量和總計收入,確保如果資料發生變化,這些數值也會隨之更新。 若要使用DataSets而非DataTables ,請參閱匯出資料集資料表指南。

輸出

專業的銷售報告Excel文件,包含訂單數據、計算總額、格式化貨幣、日期和匯總統計信息,顯示5筆訂單,總金額為7,377.20美元

利用資料庫資料自動計算與格式化,產生專業的銷售報告。

需要簡化您的 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");
$vbLabelText   $csharpLabel

如何跨多個工作表引用資料?

此範例產生完整的多工作表報表。 每個工作表都有其特定用途:銷售數據、庫存追蹤和人力資源指標。 匯總表使用跨表公式整合關鍵指標。 請注意公式中的工作表引用語法—" 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);
}
$vbLabelText   $csharpLabel

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
}
$vbLabelText   $csharpLabel

對於 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");
}
$vbLabelText   $csharpLabel

如何配置 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 文件以了解進階功能。 對於生產環境部署,請查看符合您專案要求的授權選項。 隨著需求的增長,可以考慮探索許可證延期升級途徑

IronXL 的定價方案包括 Lite(749 美元)、Plus(999 美元)、Professional(1,999 美元)和 Unlimited(3,999 美元)四種許可證,每種許可證對開發者、地點和專案數量都有不同的限制。

靈活的授權選項,滿足您從開發到企業部署的各種 Excel 產生需求。

常見問題解答

IronXL是什麼?

IronXL 是一個庫,它允許開發人員在 C# 中建立、讀取和編輯 Excel 文件,而無需 Microsoft Office 或複雜的 COM 互通。

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

您可以使用 IronXL 在 C# 中產生 Excel 文件,它提供了一個簡單的 API,可以以程式設計方式建立、格式化和操作 Excel 文件。

使用 IronXL 需要安裝 Microsoft Office 嗎?

不,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 檔案的創建,消除了複雜設定和依賴項的需求,從而簡化了開發流程。

喬迪·巴迪亞
軟體工程師
喬迪精通Python、C#和C++,除了在Iron Software運用這些技能外,他還從事遊戲程式設計。他參與產品測試、產品開發和研究等工作,為產品的持續改進做出了巨大貢獻。豐富的經驗讓他始終保持挑戰性和工作熱情,他表示這是他最喜歡在Iron Software工作的原因之一。喬迪在佛羅裡達州邁阿密長大,畢業於佛羅裡達大學,主修電腦科學和統計學。