使用 IRONXL 如何在 C# 中創建 Excel 樞紐分析表 Jordi Bardia 更新:2025年11月2日 下載 IronXL NuGet 下載 DLL 下載 開始免費試用 LLM副本 LLM副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 在需要分析和計算來源資料的商業應用程式中,以程式設計方式使用 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集合,可自動處理記憶體。 輸出 主要區別和注意事項 部署要求 Excel Interop需要: 已安裝並具有有效許可證的 Microsoft Excel Windows作業系統 正確的 COM 權限和設置 辦公室自動化伺服器配置 IronXL需要: 僅限IronXL庫包 可在任何支援.NET 的平台上運行 無需安裝 Office 或獲得許可證 簡化部署流程 程式碼品質和維護 互通性涉及謹慎管理 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 的免費試用,體驗其與眾不同之處,或瀏覽教學以查看更多範例。 準備部署? 查看許可證選項,選擇適合您任務的套餐。 常見問題解答 使用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 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。 相關文章 更新2026年3月1日 在ASP.NET C#中下載Excel文件:將數據匯出到XLSX,CSV和更多格式 使用C#和IronXL在ASP.NET Core中下載Excel文件。從MVC控制器中匯出數據到XLSX, CSV和XML,附有MemoryStream和File()返回。包括代碼範例。 閱讀更多 更新2026年3月1日 如何在Blazor中使用IronXL匯出Excel文件 學習如何在Blazor伺服器應用程式中使用IronXL将數據匯出到Excel。此指南涵蓋專案設置、服務設計、條件格式化、多表報告和錯誤處理,附有完整的C#代碼範例。 閱讀更多 更新2026年2月27日 如何在C#中而不是使用StreamReader來讀取Excel文件 了解StreamReader為何無法讀取Excel文件,並學習如何使用IronXL加載來自磁盤或內存流的XLSX和XLS工作簿。 閱讀更多 如何使用 IronXL 在 C# 中匯入 Excel 資料如何在 C# 中匯出模板
更新2026年3月1日 在ASP.NET C#中下載Excel文件:將數據匯出到XLSX,CSV和更多格式 使用C#和IronXL在ASP.NET Core中下載Excel文件。從MVC控制器中匯出數據到XLSX, CSV和XML,附有MemoryStream和File()返回。包括代碼範例。 閱讀更多
更新2026年3月1日 如何在Blazor中使用IronXL匯出Excel文件 學習如何在Blazor伺服器應用程式中使用IronXL将數據匯出到Excel。此指南涵蓋專案設置、服務設計、條件格式化、多表報告和錯誤處理,附有完整的C#代碼範例。 閱讀更多
更新2026年2月27日 如何在C#中而不是使用StreamReader來讀取Excel文件 了解StreamReader為何無法讀取Excel文件,並學習如何使用IronXL加載來自磁盤或內存流的XLSX和XLS工作簿。 閱讀更多