跳過到頁腳內容
使用 IRONXL

如何在 C# 中創建 Excel 樞紐分析表

在商業應用程式中以程式方式操作 Excel 樞紐分析表是分析和計算來源資料的常見需求。 雖然 Microsoft 的 Excel Interop 一直是建立 Excel 文件中樞紐分析表的傳統方法,但現代解決方案如IronXL提供了顯著的優勢。 本指南詳細介紹了這兩種方法並提供實際範例,幫助您使用 C# Interop 創建 Excel 中的樞紐分析表,或選擇更好的替代方案。

了解兩種方法

什麼是 Excel Interop?

Excel Interop 使用 COM (Component Object Model) 透過 C#直接控制 Microsoft Excel。 這需要在系統上安裝 Office,並基本上自動化 Excel,就像使用者在應用程式中進行交互一樣。 每個工作表、工作簿和單元格都成為可以通過代碼操作的對象。

什麼是 IronXL?

IronXL 是一個獨立的 .NET 函式庫,可以在不需要 Microsoft Office 的情況下讀取、編輯和建立 Excel 文件。它可以在 Windows、Linux、macOS 和 Docker 容器上工作,使得它非常適合現代部署場景。 您可以在不需要 COM 互操作的情況下打開、保存和匯出數據。

設定您的環境

對於 Excel Interop

Install-Package Microsoft.Office.Interop.Excel

對於 IronXL

Install-Package IronXL.Excel

或者,使用 NuGet 程式包管理器 UI 選擇“IronXL.Excel”並點擊安裝。 您也可以通過 .NET CLI 使用命令行參數安裝或直接從 GitHub 引用它。

兩個庫都可以通過 NuGet 獲得。 請注意 Excel Interop 需要完整的 Microsoft Office 安裝,而 IronXL 獨立運作。 在繼續之前,請確保您的系統滿足要求。

以 C# Interop 程式化創建 Excel 樞紐分析表

這是一個完整的範例,顯示如何使用傳統的 Interop 方法程序化地創建樞紐分析表:

using Excel = Microsoft.Office.Interop.Excel;
class Program
{
    static void Main(string[] args)
    {
        // Create Excel application instance
        var excelApp = new Excel.Application();
        var workbook = excelApp.Workbooks.Add();
                    var dataSheet = (Excel.Worksheet)workbook.Worksheets[1];
            var pivotSheet = (Excel.Worksheet)workbook.Worksheets.Add();
            // Add header row and sample data
            dataSheet.Cells[1, 1] = "Product";
            dataSheet.Cells[1, 2] = "Region";
            dataSheet.Cells[1, 3] = "Sales";
            // ... populate data rows with values
            // Add sample data rows
            dataSheet.Cells[2, 1] = "Laptop";
            dataSheet.Cells[2, 2] = "North";
            dataSheet.Cells[2, 3] = 1200;
            dataSheet.Cells[3, 1] = "Laptop";
            dataSheet.Cells[3, 2] = "South";
            dataSheet.Cells[3, 3] = 1500;
            dataSheet.Cells[4, 1] = "Phone";
            dataSheet.Cells[4, 2] = "North";
            dataSheet.Cells[4, 3] = 800;
            dataSheet.Cells[5, 1] = "Phone";
            dataSheet.Cells[5, 2] = "South";
            dataSheet.Cells[5, 3] = 950;
            dataSheet.Cells[6, 1] = "Tablet";
            dataSheet.Cells[6, 2] = "East";
            dataSheet.Cells[6, 3] = 600;
            dataSheet.Cells[7, 1] = "Tablet";
            dataSheet.Cells[7, 2] = "West";
            dataSheet.Cells[7, 3] = 750;
            dataSheet.Cells[8, 1] = "Monitor";
            dataSheet.Cells[8, 2] = "North";
            dataSheet.Cells[8, 3] = 400;
            dataSheet.Cells[9, 1] = "Monitor";
            dataSheet.Cells[9, 2] = "South";
            dataSheet.Cells[9, 3] = 500;
            dataSheet.Cells[10, 1] = "Keyboard";
            dataSheet.Cells[10, 2] = "East";
            dataSheet.Cells[10, 3] = 300;
            // Create pivot cache from source data range
            Excel.Range dataRange = dataSheet.Range["A1:C10"];
            Excel.PivotCache pivotCache = workbook.PivotCaches().Create(
                Excel.XlPivotTableSourceType.xlDatabase, dataRange);
            // Create PivotTable at specific location
            Excel.PivotTables pivotTables = (Excel.PivotTables)pivotSheet.PivotTables();
            Excel.PivotTable pivotTable = pivotTables.Add(
                pivotCache, pivotSheet.Range["A3"], "SalesPivot");
            // Configure pivot table fields - row and column headers
            ((Excel.PivotField)pivotTable.PivotFields("Product")).Orientation =
                Excel.XlPivotFieldOrientation.xlRowField;
            ((Excel.PivotField)pivotTable.PivotFields("Region")).Orientation =
                Excel.XlPivotFieldOrientation.xlColumnField;
            ((Excel.PivotField)pivotTable.PivotFields("Sales")).Orientation =
                Excel.XlPivotFieldOrientation.xlDataField;
            // Configure grand totals and formatting
            pivotTable.RowGrand = true;
            pivotTable.ColumnGrand = true;
            // Save the Excel file
            workbook.SaveAs("pivot_interop.xlsx");
            workbook.Close();
            excelApp.Quit();
            // Critical: Release COM objects to avoid errors
            #if WINDOWS
            Marshal.ReleaseComObject(pivotTable);
            Marshal.ReleaseComObject(pivotSheet);
            Marshal.ReleaseComObject(dataSheet);
            Marshal.ReleaseComObject(workbook);
            Marshal.ReleaseComObject(excelApp);
            #endif
    }
}
using Excel = Microsoft.Office.Interop.Excel;
class Program
{
    static void Main(string[] args)
    {
        // Create Excel application instance
        var excelApp = new Excel.Application();
        var workbook = excelApp.Workbooks.Add();
                    var dataSheet = (Excel.Worksheet)workbook.Worksheets[1];
            var pivotSheet = (Excel.Worksheet)workbook.Worksheets.Add();
            // Add header row and sample data
            dataSheet.Cells[1, 1] = "Product";
            dataSheet.Cells[1, 2] = "Region";
            dataSheet.Cells[1, 3] = "Sales";
            // ... populate data rows with values
            // Add sample data rows
            dataSheet.Cells[2, 1] = "Laptop";
            dataSheet.Cells[2, 2] = "North";
            dataSheet.Cells[2, 3] = 1200;
            dataSheet.Cells[3, 1] = "Laptop";
            dataSheet.Cells[3, 2] = "South";
            dataSheet.Cells[3, 3] = 1500;
            dataSheet.Cells[4, 1] = "Phone";
            dataSheet.Cells[4, 2] = "North";
            dataSheet.Cells[4, 3] = 800;
            dataSheet.Cells[5, 1] = "Phone";
            dataSheet.Cells[5, 2] = "South";
            dataSheet.Cells[5, 3] = 950;
            dataSheet.Cells[6, 1] = "Tablet";
            dataSheet.Cells[6, 2] = "East";
            dataSheet.Cells[6, 3] = 600;
            dataSheet.Cells[7, 1] = "Tablet";
            dataSheet.Cells[7, 2] = "West";
            dataSheet.Cells[7, 3] = 750;
            dataSheet.Cells[8, 1] = "Monitor";
            dataSheet.Cells[8, 2] = "North";
            dataSheet.Cells[8, 3] = 400;
            dataSheet.Cells[9, 1] = "Monitor";
            dataSheet.Cells[9, 2] = "South";
            dataSheet.Cells[9, 3] = 500;
            dataSheet.Cells[10, 1] = "Keyboard";
            dataSheet.Cells[10, 2] = "East";
            dataSheet.Cells[10, 3] = 300;
            // Create pivot cache from source data range
            Excel.Range dataRange = dataSheet.Range["A1:C10"];
            Excel.PivotCache pivotCache = workbook.PivotCaches().Create(
                Excel.XlPivotTableSourceType.xlDatabase, dataRange);
            // Create PivotTable at specific location
            Excel.PivotTables pivotTables = (Excel.PivotTables)pivotSheet.PivotTables();
            Excel.PivotTable pivotTable = pivotTables.Add(
                pivotCache, pivotSheet.Range["A3"], "SalesPivot");
            // Configure pivot table fields - row and column headers
            ((Excel.PivotField)pivotTable.PivotFields("Product")).Orientation =
                Excel.XlPivotFieldOrientation.xlRowField;
            ((Excel.PivotField)pivotTable.PivotFields("Region")).Orientation =
                Excel.XlPivotFieldOrientation.xlColumnField;
            ((Excel.PivotField)pivotTable.PivotFields("Sales")).Orientation =
                Excel.XlPivotFieldOrientation.xlDataField;
            // Configure grand totals and formatting
            pivotTable.RowGrand = true;
            pivotTable.ColumnGrand = true;
            // Save the Excel file
            workbook.SaveAs("pivot_interop.xlsx");
            workbook.Close();
            excelApp.Quit();
            // Critical: Release COM objects to avoid errors
            #if WINDOWS
            Marshal.ReleaseComObject(pivotTable);
            Marshal.ReleaseComObject(pivotSheet);
            Marshal.ReleaseComObject(dataSheet);
            Marshal.ReleaseComObject(workbook);
            Marshal.ReleaseComObject(excelApp);
            #endif
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此代碼創建 Excel 應用程式,添加一個包含數據源和標題行的工作表,建立樞紐快取,構建樞紐分析表對象,並配置字段方向。 清理部分至關重要——未能釋放 COM 對象會導致記憶體洩漏。 每個單元、範圍和工作表都必須妥善處置以避免運行時錯誤。

IronXL 替代方法

IronXL 透過直接處理 Excel 文件格式來採用不同的方法。 以下是如何程序化地達到類似分析結果:

using IronXL;
using System.Linq;
class Program 
{
    static void Main(string[] args)
    {
        // Create workbook and add worksheet with data
        WorkBook workbook = WorkBook.Create();
        WorkSheet sheet = workbook.CreateWorkSheet("Data");
        // Add header row to define column structure
        sheet["A1"].Value = "Product";
        sheet["B1"].Value = "Region";
        sheet["C1"].Value = "Sales";
        // Add sample data to cells
        sheet["A2"].Value = "Widget";
        sheet["B2"].Value = "North";
        sheet["C2"].Value = 1500;
        // ... continue to add more data rows
        sheet["A3"].Value = "Laptop";
        sheet["B3"].Value = "South";
        sheet["C3"].Value = 1500;
        sheet["A4"].Value = "Phone";
        sheet["B4"].Value = "North";
        sheet["C4"].Value = 800;
        sheet["A5"].Value = "Phone";
        sheet["B5"].Value = "South";
        sheet["C5"].Value = 950;
        sheet["A6"].Value = "Tablet";
        sheet["B6"].Value = "East";
        sheet["C6"].Value = 600;
        sheet["A7"].Value = "Tablet";
        sheet["B7"].Value = "West";
        sheet["C7"].Value = 750;
        sheet["A8"].Value = "Monitor";
        sheet["B8"].Value = "North";
        sheet["C8"].Value = 400;
        sheet["A9"].Value = "Monitor";
        sheet["B9"].Value = "South";
        sheet["C9"].Value = 500;
        sheet["A10"].Value = "Keyboard";
        sheet["B10"].Value = "East";
        sheet["C10"].Value = 300;
        // Create summary analysis worksheet
        var summarySheet = workbook.CreateWorkSheet("Summary");
        // Group and calculate aggregated data
        var data = sheet["A1:C10"].ToDataTable(true);
        var productSummary = data.AsEnumerable()
            .GroupBy(row => row.Field<string>("Product"))
            .Select((group, index) => new {
                Product = group.Key,
                TotalSales = group.Sum(r => Convert.ToDecimal(r["Sales"])),
                Count = group.Count(),
                RowIndex = index + 2
            });
        // Write column headers for summary
        summarySheet["A1"].Value = "Product Summary";
        summarySheet["A2"].Value = "Product";
        summarySheet["B2"].Value = "Total Sales";
        summarySheet["C2"].Value = "Count";
        // Export results to cells
        foreach (var item in productSummary)
        {
            summarySheet[$"A{item.RowIndex + 1}"].Value = item.Product;
            summarySheet[$"B{item.RowIndex + 1}"].Value = item.TotalSales;
            summarySheet[$"C{item.RowIndex + 1}"].Value = item.Count;
        }
        // Apply number formatting and style
        summarySheet["B:B"].FormatString = "$#,##0.00";
        // Save the xlsx file
        workbook.SaveAs("analysis_ironxl.xlsx");
    }
}
using IronXL;
using System.Linq;
class Program 
{
    static void Main(string[] args)
    {
        // Create workbook and add worksheet with data
        WorkBook workbook = WorkBook.Create();
        WorkSheet sheet = workbook.CreateWorkSheet("Data");
        // Add header row to define column structure
        sheet["A1"].Value = "Product";
        sheet["B1"].Value = "Region";
        sheet["C1"].Value = "Sales";
        // Add sample data to cells
        sheet["A2"].Value = "Widget";
        sheet["B2"].Value = "North";
        sheet["C2"].Value = 1500;
        // ... continue to add more data rows
        sheet["A3"].Value = "Laptop";
        sheet["B3"].Value = "South";
        sheet["C3"].Value = 1500;
        sheet["A4"].Value = "Phone";
        sheet["B4"].Value = "North";
        sheet["C4"].Value = 800;
        sheet["A5"].Value = "Phone";
        sheet["B5"].Value = "South";
        sheet["C5"].Value = 950;
        sheet["A6"].Value = "Tablet";
        sheet["B6"].Value = "East";
        sheet["C6"].Value = 600;
        sheet["A7"].Value = "Tablet";
        sheet["B7"].Value = "West";
        sheet["C7"].Value = 750;
        sheet["A8"].Value = "Monitor";
        sheet["B8"].Value = "North";
        sheet["C8"].Value = 400;
        sheet["A9"].Value = "Monitor";
        sheet["B9"].Value = "South";
        sheet["C9"].Value = 500;
        sheet["A10"].Value = "Keyboard";
        sheet["B10"].Value = "East";
        sheet["C10"].Value = 300;
        // Create summary analysis worksheet
        var summarySheet = workbook.CreateWorkSheet("Summary");
        // Group and calculate aggregated data
        var data = sheet["A1:C10"].ToDataTable(true);
        var productSummary = data.AsEnumerable()
            .GroupBy(row => row.Field<string>("Product"))
            .Select((group, index) => new {
                Product = group.Key,
                TotalSales = group.Sum(r => Convert.ToDecimal(r["Sales"])),
                Count = group.Count(),
                RowIndex = index + 2
            });
        // Write column headers for summary
        summarySheet["A1"].Value = "Product Summary";
        summarySheet["A2"].Value = "Product";
        summarySheet["B2"].Value = "Total Sales";
        summarySheet["C2"].Value = "Count";
        // Export results to cells
        foreach (var item in productSummary)
        {
            summarySheet[$"A{item.RowIndex + 1}"].Value = item.Product;
            summarySheet[$"B{item.RowIndex + 1}"].Value = item.TotalSales;
            summarySheet[$"C{item.RowIndex + 1}"].Value = item.Count;
        }
        // Apply number formatting and style
        summarySheet["B:B"].FormatString = "$#,##0.00";
        // Save the xlsx file
        workbook.SaveAs("analysis_ironxl.xlsx");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

這個 IronXL 範例展示了如何建立工作簿、添加工作表、填充單元格數據並執行聚合分析。 代碼按產品分組數據並計算總和和計數,創建摘要報告。 不需要管理 COM 對象,方法是直接的 .NET 集合,能夠自動處理記憶體。

輸出

如何在 C# 中創建 Excel 樞紐分析表:圖6 - IronXL 輸出

如何在 C# 中創建 Excel 樞紐分析表:圖7 - 摘要輸出

主要差異與考量

部署要求

Excel Interop要求:

  • 安裝 Microsoft Excel 並具合法授權
  • Windows 作業系統
  • 正確的 COM 權限和設定
  • Office 自動化的伺服器配置 IronXL要求:

  • 只有 IronXL 函式庫套裝
  • 可在支援 .NET 的任何平臺上運作
  • 無需 Office 安裝或授權
  • 簡化的部署過程

如何在 C# 中創建 Excel 樞紐分析表:圖8 - 功能

代碼品質和維護

Interop 涉及仔細管理 COM 對象以避免記憶體洩漏和錯誤。 創建的每個 Excel 對象都必須使用正確的方法顯式釋放。 IronXL 使用標準的 .NET 對象配有自動垃圾收集,從而降低資源問題的風險。

錯誤處理

在 Interop 中,錯誤常涉及到 Excel 可用性、版本差異或 COM 失敗。 IronXL 錯誤是標準的 .NET 例外,使除錯更加簡單。 您可以依賴熟悉的 try-catch 模式,而無需擔心特定於 COM 的問題。

最佳實踐和建議

選擇 Excel Interop 的情況:

  • 您需要具有所有格式化選項的精確 Excel 樞紐分析表功能
  • 確保系統上有 Excel
  • 僅限於 Windows 桌面應用程式開發
  • 需要遺留代碼要求 選擇 IronXL 的情況:

  • 構建伺服器應用程序或網頁解決方案
  • 需要跨平台兼容性
  • 需要在不需要 COM 開銷的情況下驅動可靠的性能
  • 部署到容器或雲環境

訪問 IronXL文檔了解更多實施細節。 如有問題或需要支援,請聯繫 Iron Software 團隊。

結論

雖然 C# Interop 提供了直接在 Excel 中創建樞紐分析表功能,但它帶來了部署限制和複雜性。 IronXL 提供了一種現代替代方案,簡化 Excel 文件操作,同時提供在任何支援 .NET 的地方運行的靈活性。

對於構建新應用或現代化現有解決方案的開發人員來說,IronXL 的方法消除了 COM InterOp 的開銷,同時提供強大的數據處理能力。 無論您需要讀取、編輯還是導出 Excel 數據,IronXL 提供了一個更清潔的解決方案。

開始使用 IronXL 的免費試用 以體驗不同,或探索教程以查看更多範例。 準備部署? 查看授權選項以選擇適合您工作的套裝。

如何在 C# 中創建 Excel 樞紐分析表:圖9 - 授權

常見問題解答

使用IronXL而非Excel Interop來創建樞紐分析表的優勢是什麼?

IronXL提供了顯著優於Excel Interop的優勢,包括易用性、更好的性能,以及無需在服務器上安裝Excel即可創建樞紐分析表的能力。

我可以在C#中不使用Excel Interop建立Excel樞紐分析表嗎?

是的,您可以使用IronXL在C#中建立Excel樞紐分析表,這提供了一種現代且有效的替代Excel Interop的解決方案。

使用 IronXL 是否需要安裝 Microsoft Excel?

不,IronXL不需要在您的系統上安裝Microsoft Excel,使其成為一種靈活的解決方案來創建和管理Excel文件。

使用IronXL在Excel中建立樞紐分析表的步驟是什麼?

要使用IronXL建立樞紐分析表,首先,載入您的Excel文件,指定數據範圍,定義樞紐分析表字段,然後生成樞紐分析表。IronXL的全面API使得這一過程變得簡單明瞭。

除了樞紐分析表外,IronXL是否支持其他的Excel功能?

是的,IronXL支持多種Excel功能,包括讀取和寫入Excel文件、格式化單元格以及執行計算等。

IronXL在創建樞紐分析表時如何處理大型數據集?

IronXL旨在有效處理大型數據集,即便面對龐大的數據時,也能快速可靠地創建樞紐分析表。

IronXL可以用於雲端應用程式嗎?

是的,IronXL可以整合到基於雲的應用程式中,提供管理雲端Excel文件的無縫解決方案。

IronXL支持哪些編程語言來創建樞紐分析表?

IronXL主要支持C#,使其可以輕鬆在.NET應用程式中創建樞紐分析表和執行其他Excel操作。

是否有可用的教程來學習如何使用IronXL?

是的,Iron Software在其網站上提供了全面的文檔和教程,幫助用戶學習如何有效地使用IronXL。

IronXL 提供哪些許可選項?

IronXL提供了不同的許可選項,包括免費和付費方案,以滿足不同項目需求和規模。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。