IRONSOFTWAREHOME
USING IRONXL

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

Curtis Chau
Curtis Chau
Updated: 2026年4月21日

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

了解兩種方法

什麼是Excel Interop?

Excel Interop使用COM(組件物件模型)直接透過C#控制Microsoft Excel。 這需要在系統上安裝Office,並實質上將Excel自動化,就像使用者在與應用程式互動一樣。 每個工作表、工作簿和單元格都成為可通過程式碼操控的物件。

什麼是IronXL?

IronXL是一個獨立的.NET程式庫,可以讀取、編輯和建立Excel文件,而不需要Microsoft Office。它可以跨Windows、Linux、macOS和Docker容器工作,非常適合現代部署場景。 您可以開啟、儲存和匯出資料,而不需要COM interop的開銷。

設定您的環境

對於Excel Interop

PM > Install-Package Microsoft.Office.Interop.Excel

對於IronXL

PM > 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
    }
}

此程式碼建立一個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");
    }
}

此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的免費試用以體驗不同,或探索教程以了解更多範例。 準備就緒進行部署嗎? 查看授權選項以選擇適合您任務的套件。

Curtis Chau
技術作家

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

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預約您的免費即時演示
Booking Badge

全球數百萬工程師的信賴

Iron Software的客戶標誌
獲得無義務諮詢
填寫以下表格或電郵sales@ironsoftware.com
您的資料將始終保密。
全球數百萬工程師的信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立