跳過到頁腳內容
使用 IRONXL

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

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

了解兩種方法

什麼是Excel互通性?

Excel Interop 使用 COM(元件物件模型)透過 C# 直接控制 Microsoft Excel。 它需要係統上安裝 Office,並且本質上是自動執行 Excel 操作,就像使用者與應用程式互動一樣。 每個工作表、工作簿和儲存格都會變成一個對象,您可以透過程式碼對其進行操作。

IronXL是什麼?

IronXL是一個獨立的.NET庫,無需 Microsoft Office 即可讀取、編輯和建立 Excel 檔案。它可在 Windows、Linux、macOS 和 Docker 容器中運行,是現代部署場景的理想選擇。 您可以開啟、儲存和匯出數據,而無需 COM 互通性帶來的額外開銷。

設定您的環境

Excel 互通

Install-Package Microsoft.Office.Interop.Excel

適用於IronXL

Install-Package IronXL.Excel

或者,使用NuGet套件管理器 UI,搜尋"IronXl.Excel"並按一下安裝。 您也可以透過.NET CLI 使用命令參數進行安裝,或直接從GitHub引用它。

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

Creating an Excel Pivot Table Programmatically with C# 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
    }
}
$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");
    }
}
$vbLabelText   $csharpLabel

本IronXL範例示範如何建立工作簿、新增工作表、以資料填入儲存格以及執行聚合分析。 程式碼依產品將資料分組,計算總數和計數,產生總計報告。 無需管理 COM 對象,這些方法是簡單的.NET集合,可自動處理記憶體。

輸出

如何在 C# 中建立 Excel 資料透視表:圖 6 - IronXL輸出

如何在 C# 中建立 Excel 資料透視表:圖 7 - 匯總輸出

主要區別和注意事項

部署要求

Excel Interop需要:

  • 已安裝並具有有效許可證的 Microsoft Excel
  • Windows作業系統
  • 正確的 COM 權限和設置
  • 辦公室自動化伺服器配置 IronXL需要:

  • 僅限IronXL庫包
  • 可在任何支援.NET 的平台上運行 無需安裝 Office 或獲得許可證
  • 簡化部署流程

如何在 C# 中建立 Excel 資料透視表:圖 8 - 功能

程式碼品質和維護

互通性涉及謹慎管理 COM 對象,以避免記憶體洩漏和錯誤。 每個建立的 Excel 物件都必須使用正確的方法明確釋放。 IronXL使用具有自動垃圾回收功能的標準.NET對象,從而降低了資源問題的風險。

錯誤處理

使用 Interop 時,錯誤通常與 Excel 的可用性、版本差異或 COM 故障有關。 IronXL錯誤是標準的.NET異常,這使得調試更加直接。 您可以依賴熟悉的 try-catch 模式,而無需擔心 COM 特有的問題。

最佳實踐和建議

在以下情況下選擇 Excel Interop:

您需要具備所有格式選項的 Excel 資料透視表功能。 系統上保證提供Excel軟體。

  • 僅適用於 Windows 桌面應用程式
  • 遺留程式碼要求 選擇IronXL 的情況:

  • 建立伺服器應用程式或 Web 解決方案
  • 需要跨平台相容性
  • 需要可靠的效能,且無 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 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我