跳過到頁腳內容
使用 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 可獨立運作。 在繼續操作之前,請確保您的系統符合要求。

使用 C# Interop 以程式設計方式建立 Excel 資料透視表

以下是一個完整的範例,展示如何使用傳統的互通方法以程式設計方式建立資料透視表:

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 權限和設置
  • 辦公室自動化伺服器配置 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 - 許可

常見問題解答

與 Excel Interop 相比,使用 IronXL 製作透視表有何優勢?

與 Excel Interop 相比,IronXL 具有顯著的優勢,包括易用性、更佳的效能,以及無需在伺服器上安裝 Excel 即可建立資料透視表的能力。

我可以在不使用 Excel Interop 的情況下用 C# 建立 Excel 資料透視表嗎?

是的,您可以使用 IronXL 在 C# 中建立 Excel 資料透視表,IronXL.Excel 提供了現代化且高效率的 Excel Interop 替代方案。

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

不需要,IronXL.Excel 不需要在您的系統上安裝 Microsoft Excel,使其成為建立和管理 Excel 檔案的靈活解決方案。

使用 IronXL.Excel 在 Excel 中建立資料透視表的步驟為何?

要使用 IronXL 建立資料透視表,首先,載入您的 Excel 檔案、指定資料範圍、定義您的資料透視表欄位,然後產生資料透視表。IronXL 全面的 API 使這個過程簡單直接。

IronXL.Excel 是否支援除資料透視表以外的其他 Excel 功能?

是的,IronXL.Excel 支援廣泛的 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 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。