使用 IRONXL 如何在 C# 中建立 Excel 資料透視表? Curtis Chau 更新:2025年10月19日 下載 IronXL NuGet 下載 DLL 下載 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 在 C# 中建立 Excel 資料透視表既可以使用 Office Interop(需要安裝 Microsoft Office),也可以使用 IronXL 等獨立運作的現代函式庫,其中 IronXL 為DevOps環境提供了更優越的部署彈性和跨平台支援。 以程式設計方式產生資料透視表需要使用 C# 互通 及其 Office 依賴項,或使用像IronXL這樣可以獨立工作的現代函式庫。 本教學示範了這兩種方法,重點介紹了為什麼開發人員越來越多地選擇 IronXL 而不是傳統的互通方法,尤其是在部署到Docker 容器或Azure和AWS等雲端環境時。 在本文中,我們將學習如何編輯、建立、設計和計算透視表和分組,並進行自動分析和錯誤處理——所有這些都將保持DevOps工程師所需的部署簡易性。 什麼是Excel資料透視表? 資料透視表是Excel最強大的工具之一。 它是一種匯總大型資料集的簡單方法,使其在 .NET 應用程式的資料分析中具有不可估量的價值。 資料透視表可以幫助您輕鬆顯示、理解和分析數值資料。 它們不僅在 Excel 中可用,而且在其他程式中也可用,例如 Google Sheets、Apple Numbers 和CSV Exports 。 它們提供了一種查看數據概覽的解決方案——充當數據控制台,讓人們能夠以有意義的方式查看自己的資訊。 對於容器化應用程序,以程式設計方式建立資料透視表可以消除在 Docker 映像中安裝 Excel 的需要,從而顯著減少容器大小和部署複雜性。 這種方法與現代 CI/CD 管線和容器部署策略完美契合。 讓我們先來探討一下建立資料透視表的錯誤方法,然後再學習 C# 中的正確方法: 如何使用 C# 互通 在 Excel 表格中建立資料透視表? C# Excel Interop 透過 COM 自動化提供對 Excel 資料透視表功能的直接存取。 以下是許多開發人員在尋找用於在 C# 中產生資料透視表的工具時遇到的傳統方法: 為什麼這種方法在 .NET 中被認為已經過時? using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; // Create Excel application instance Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Data\SalesData.xlsx"); Excel.Worksheet xlSheet = (Excel.Worksheet)xlWorkbook.Sheets[1]; Excel.Worksheet xlPivotSheet = (Excel.Worksheet)xlWorkbook.Sheets.Add(); // Define data range for pivot table Excel.Range dataRange = xlSheet.UsedRange; // Row area and column area // Create pivot cache and pivot table Excel.PivotCache pivotCache = xlWorkbook.PivotCaches().Create( Excel.XlPivotTableSourceType.xlDatabase, dataRange, Type.Missing); Excel.PivotTable pivotTable = pivotCache.CreatePivotTable( xlPivotSheet.Cells[3, 1], "SalesPivot", Type.Missing, Type.Missing); // fields by field // Configure pivot table fields Excel.PivotField productField = (Excel.PivotField)pivotTable.PivotFields("Product"); productField.Orientation = Excel.XlPivotFieldOrientation.xlRowField; productField.Position = 1; Excel.PivotField regionField = (Excel.PivotField)pivotTable.PivotFields("Region"); regionField.Orientation = Excel.XlPivotFieldOrientation.xlColumnField; regionField.Position = 1; Excel.PivotField salesField = (Excel.PivotField)pivotTable.PivotFields("Sales"); pivotTable.AddDataField(salesField, "Sum of Sales", Excel.XlConsolidationFunction.xlSum); // Save and cleanup xlWorkbook.SaveAs(@"C:\Data\PivotReport.xlsx"); xlWorkbook.Close(); xlApp.Quit(); // Release COM objects to prevent memory leaks Marshal.ReleaseComObject(pivotTable); Marshal.ReleaseComObject(pivotCache); Marshal.ReleaseComObject(xlPivotSheet); Marshal.ReleaseComObject(xlSheet); Marshal.ReleaseComObject(xlWorkbook); Marshal.ReleaseComObject(xlApp); using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; // Create Excel application instance Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Data\SalesData.xlsx"); Excel.Worksheet xlSheet = (Excel.Worksheet)xlWorkbook.Sheets[1]; Excel.Worksheet xlPivotSheet = (Excel.Worksheet)xlWorkbook.Sheets.Add(); // Define data range for pivot table Excel.Range dataRange = xlSheet.UsedRange; // Row area and column area // Create pivot cache and pivot table Excel.PivotCache pivotCache = xlWorkbook.PivotCaches().Create( Excel.XlPivotTableSourceType.xlDatabase, dataRange, Type.Missing); Excel.PivotTable pivotTable = pivotCache.CreatePivotTable( xlPivotSheet.Cells[3, 1], "SalesPivot", Type.Missing, Type.Missing); // fields by field // Configure pivot table fields Excel.PivotField productField = (Excel.PivotField)pivotTable.PivotFields("Product"); productField.Orientation = Excel.XlPivotFieldOrientation.xlRowField; productField.Position = 1; Excel.PivotField regionField = (Excel.PivotField)pivotTable.PivotFields("Region"); regionField.Orientation = Excel.XlPivotFieldOrientation.xlColumnField; regionField.Position = 1; Excel.PivotField salesField = (Excel.PivotField)pivotTable.PivotFields("Sales"); pivotTable.AddDataField(salesField, "Sum of Sales", Excel.XlConsolidationFunction.xlSum); // Save and cleanup xlWorkbook.SaveAs(@"C:\Data\PivotReport.xlsx"); xlWorkbook.Close(); xlApp.Quit(); // Release COM objects to prevent memory leaks Marshal.ReleaseComObject(pivotTable); Marshal.ReleaseComObject(pivotCache); Marshal.ReleaseComObject(xlPivotSheet); Marshal.ReleaseComObject(xlSheet); Marshal.ReleaseComObject(xlWorkbook); Marshal.ReleaseComObject(xlApp); Imports Excel = Microsoft.Office.Interop.Excel Imports System.Runtime.InteropServices ' Create Excel application instance Dim xlApp As New Excel.Application() Dim xlWorkbook As Excel.Workbook = xlApp.Workbooks.Open("C:\Data\SalesData.xlsx") Dim xlSheet As Excel.Worksheet = CType(xlWorkbook.Sheets(1), Excel.Worksheet) Dim xlPivotSheet As Excel.Worksheet = CType(xlWorkbook.Sheets.Add(), Excel.Worksheet) ' Define data range for pivot table Dim dataRange As Excel.Range = xlSheet.UsedRange ' Create pivot cache and pivot table Dim pivotCache As Excel.PivotCache = xlWorkbook.PivotCaches().Create(Excel.XlPivotTableSourceType.xlDatabase, dataRange, Type.Missing) Dim pivotTable As Excel.PivotTable = pivotCache.CreatePivotTable(xlPivotSheet.Cells(3, 1), "SalesPivot", Type.Missing, Type.Missing) ' Configure pivot table fields Dim productField As Excel.PivotField = CType(pivotTable.PivotFields("Product"), Excel.PivotField) productField.Orientation = Excel.XlPivotFieldOrientation.xlRowField productField.Position = 1 Dim regionField As Excel.PivotField = CType(pivotTable.PivotFields("Region"), Excel.PivotField) regionField.Orientation = Excel.XlPivotFieldOrientation.xlColumnField regionField.Position = 1 Dim salesField As Excel.PivotField = CType(pivotTable.PivotFields("Sales"), Excel.PivotField) pivotTable.AddDataField(salesField, "Sum of Sales", Excel.XlConsolidationFunction.xlSum) ' Save and cleanup xlWorkbook.SaveAs("C:\Data\PivotReport.xlsx") xlWorkbook.Close() xlApp.Quit() ' Release COM objects to prevent memory leaks Marshal.ReleaseComObject(pivotTable) Marshal.ReleaseComObject(pivotCache) Marshal.ReleaseComObject(xlPivotSheet) Marshal.ReleaseComObject(xlSheet) Marshal.ReleaseComObject(xlWorkbook) Marshal.ReleaseComObject(xlApp) $vbLabelText $csharpLabel 此 Interop 範例建立了一個原生 Excel 資料透視表,其中產品為行,地區為列,銷售額匯總在資料區中。 雖然這種方法可行,但需要安裝 Microsoft Office 並進行仔細的 COM 物件管理。 微軟的文檔解釋了為什麼這種方法已經過時。 從DevOps角度來看,這種方法尤其成問題,因為它無法有效地容器化——你無法在Linux Docker 容器中安裝 Microsoft Office,也無法部署到無伺服器環境中。 C# 互通會帶來哪些問題? 互通性方法存在一些重大挑戰,使其不適用於現代DevOps實踐和雲端原生部署。 不幸的是,Stack Overflow 和其他程式設計網站仍然推薦它,因為它們的思維方式還停留在 2000 年代初期的討論貼文中。 部署相依性:需要在執行原始碼的每台機器上安裝 Microsoft Office,包括生產伺服器。 這會增加許可成本和部署複雜性。 記憶體管理:必須使用 Marshal.ReleaseComObject() 明確釋放 COM 物件。 即使缺少一個物件也會導致 Excel 進程在記憶體中掛起, Stack Overflow 上對此有大量記錄。 考慮樞軸緩存。 平台限制:此解決方案僅適用於已安裝 Office 的 Windows 系統。 它可能運行速度極慢,並導致記憶體洩漏。 不支援Linux 、 macOS 、Docker 容器或Azure Functions等雲端平台。 這嚴重限制了部署選項,並阻礙了現代容器編排平台的使用。 效能問題:啟動 Excel 應用程式執行個體速度慢且資源消耗大,尤其是伺服器端處理。 版本相容性:不同 Office 版本可能具有不同的 COM 接口,從而導致跨環境的相容性問題。 IronXL 如何在不使用互通的情況下以程式設計方式建立資料透視表? IronXL使用託管程式碼建立資料透視表,沒有 COM 依賴項,其建立方式有所不同。 雖然它不能建立原生的 Excel 資料透視表,但它提供了強大的聚合功能,非常適合容器化部署和雲端原生架構。 該庫的效能優化包括速度提升 40 倍,記憶體使用量從 19.5 GB 減少到 1 GB 以下,使其成為資源受限的容器環境的理想選擇。 這種方法對於 XLSX 或 XLS 檔案來說有何現代之處? using IronXL; using System.Linq; using System.Data; // Keep this namespace using static System.Data.DataTableExtensions; // Use 'using static' for DataTableExtensions class Program { static void Main(string[] args) { // Load Excel file - no Office required WorkBook workbook = WorkBook.Load("SalesData.xlsx"); WorkSheet dataSheet = workbook.WorkSheets[0]; // Convert to DataTable for powerful manipulation var dataTable = dataSheet.ToDataTable(true); // true = use first row as column headers // Create pivot-style aggregation using LINQ var pivotData = dataTable.AsEnumerable() .GroupBy(row => new { Product = row["Product"].ToString(), Region = row["Region"].ToString() }) //range .Select(g => new { Product = g.Key.Product, Region = g.Key.Region, TotalSales = g.Sum(row => Convert.ToDecimal(row["Sales"])), AverageSale = g.Average(row => Convert.ToDecimal(row["Sales"])), Count = g.Count() }); // Create pivot report worksheet WorkSheet pivotSheet = workbook.CreateWorkSheet("PivotReport"); // Build cross-tabulation structure var products = pivotData.Select(p => p.Product).Distinct().OrderBy(p => p); var regions = pivotData.Select(p => p.Region).Distinct().OrderBy(r => r); // Create headers pivotSheet["A1"].Value = "Product/Region"; int col = 2; foreach (var region in regions) { pivotSheet[$"{(char)('A' + col - 1)}1"].Value = region; // string col++; } // Populate pivot data int row = 2; foreach (var product in products) { pivotSheet[$"A{row}"].Value = product; col = 2; foreach (var region in regions) { var sales = pivotData .Where(p => p.Product == product && p.Region == region) .Select(p => p.TotalSales) .FirstOrDefault(); pivotSheet[$"{(char)('A' + col - 1)}{row}"].Value = sales; col++; } row++; } // Add totals using Excel formulas pivotSheet[$"A{row}"].Value = "Total"; // grand totals for (int c = 2; c <= regions.Count() + 1; c++) { pivotSheet[$"{(char)('A' + c - 1)}{row}"].Formula = $"=SUM({(char)('A' + c - 1)}2:{(char)('A' + c - 1)}{row - 1})"; } // Proceeding to apply formatting var dataRange = pivotSheet[$"B2:{(char)('A' + regions.Count())}{row}"]; dataRange.FormatString = "$#,##0.00"; workbook.SaveAs("PivotReport.xlsx"); } } using IronXL; using System.Linq; using System.Data; // Keep this namespace using static System.Data.DataTableExtensions; // Use 'using static' for DataTableExtensions class Program { static void Main(string[] args) { // Load Excel file - no Office required WorkBook workbook = WorkBook.Load("SalesData.xlsx"); WorkSheet dataSheet = workbook.WorkSheets[0]; // Convert to DataTable for powerful manipulation var dataTable = dataSheet.ToDataTable(true); // true = use first row as column headers // Create pivot-style aggregation using LINQ var pivotData = dataTable.AsEnumerable() .GroupBy(row => new { Product = row["Product"].ToString(), Region = row["Region"].ToString() }) //range .Select(g => new { Product = g.Key.Product, Region = g.Key.Region, TotalSales = g.Sum(row => Convert.ToDecimal(row["Sales"])), AverageSale = g.Average(row => Convert.ToDecimal(row["Sales"])), Count = g.Count() }); // Create pivot report worksheet WorkSheet pivotSheet = workbook.CreateWorkSheet("PivotReport"); // Build cross-tabulation structure var products = pivotData.Select(p => p.Product).Distinct().OrderBy(p => p); var regions = pivotData.Select(p => p.Region).Distinct().OrderBy(r => r); // Create headers pivotSheet["A1"].Value = "Product/Region"; int col = 2; foreach (var region in regions) { pivotSheet[$"{(char)('A' + col - 1)}1"].Value = region; // string col++; } // Populate pivot data int row = 2; foreach (var product in products) { pivotSheet[$"A{row}"].Value = product; col = 2; foreach (var region in regions) { var sales = pivotData .Where(p => p.Product == product && p.Region == region) .Select(p => p.TotalSales) .FirstOrDefault(); pivotSheet[$"{(char)('A' + col - 1)}{row}"].Value = sales; col++; } row++; } // Add totals using Excel formulas pivotSheet[$"A{row}"].Value = "Total"; // grand totals for (int c = 2; c <= regions.Count() + 1; c++) { pivotSheet[$"{(char)('A' + c - 1)}{row}"].Formula = $"=SUM({(char)('A' + c - 1)}2:{(char)('A' + c - 1)}{row - 1})"; } // Proceeding to apply formatting var dataRange = pivotSheet[$"B2:{(char)('A' + regions.Count())}{row}"]; dataRange.FormatString = "$#,##0.00"; workbook.SaveAs("PivotReport.xlsx"); } } Imports IronXL Imports System.Linq Imports System.Data ' Keep this namespace Imports static System.Data.DataTableExtensions ' Use 'using static' for DataTableExtensions Module Program Sub Main(args As String()) ' Load Excel file - no Office required Dim workbook As WorkBook = WorkBook.Load("SalesData.xlsx") Dim dataSheet As WorkSheet = workbook.WorkSheets(0) ' Convert to DataTable for powerful manipulation Dim dataTable = dataSheet.ToDataTable(True) ' true = use first row as column headers ' Create pivot-style aggregation using LINQ Dim pivotData = dataTable.AsEnumerable() _ .GroupBy(Function(row) New With { Key .Product = row("Product").ToString(), Key .Region = row("Region").ToString() }) _ .Select(Function(g) New With { Key .Product = g.Key.Product, Key .Region = g.Key.Region, Key .TotalSales = g.Sum(Function(row) Convert.ToDecimal(row("Sales"))), Key .AverageSale = g.Average(Function(row) Convert.ToDecimal(row("Sales"))), Key .Count = g.Count() }) ' Create pivot report worksheet Dim pivotSheet As WorkSheet = workbook.CreateWorkSheet("PivotReport") ' Build cross-tabulation structure Dim products = pivotData.Select(Function(p) p.Product).Distinct().OrderBy(Function(p) p) Dim regions = pivotData.Select(Function(p) p.Region).Distinct().OrderBy(Function(r) r) ' Create headers pivotSheet("A1").Value = "Product/Region" Dim col As Integer = 2 For Each region In regions pivotSheet($"{ChrW(AscW("A"c) + col - 1)}1").Value = region ' string col += 1 Next ' Populate pivot data Dim row As Integer = 2 For Each product In products pivotSheet($"A{row}").Value = product col = 2 For Each region In regions Dim sales = pivotData _ .Where(Function(p) p.Product = product AndAlso p.Region = region) _ .Select(Function(p) p.TotalSales) _ .FirstOrDefault() pivotSheet($"{ChrW(AscW("A"c) + col - 1)}{row}").Value = sales col += 1 Next row += 1 Next ' Add totals using Excel formulas pivotSheet($"A{row}").Value = "Total" ' grand totals For c As Integer = 2 To regions.Count() + 1 pivotSheet($"{ChrW(AscW("A"c) + c - 1)}{row}").Formula = $"=SUM({ChrW(AscW("A"c) + c - 1)}2:{ChrW(AscW("A"c) + c - 1)}{row - 1})" Next ' Proceeding to apply formatting Dim dataRange = pivotSheet($"B2:{ChrW(AscW("A"c) + regions.Count())}{row}") dataRange.FormatString = "$#,##0.00" workbook.SaveAs("PivotReport.xlsx") End Sub End Module $vbLabelText $csharpLabel 這就是以容器友善方式建立資料透視表的方法。 這種方法可以在 Docker 容器、Kubernetes pod 和無伺服器函數中無縫運行,無需任何外部相依性。 整個應用程式可以打包成一個輕量級容器鏡像,在任何支援 .NET 的環境中運行。 資料透視表的輸出結果是什麼樣子的? ! 比較原始Excel銷售數據和產生的透視表,顯示按地區匯總的產品銷售額及總計 輸出結果顯示了 IronXL 如何將原始銷售資料轉換為結構化的透視報告,而無需安裝 Excel,這使其非常適合 CI/CD 管道中的自動化報告。 如何使用 IronXL 公式建立動態匯總? 對於需要類似資料透視表刷新功能的動態更新場景,IronXL 可以利用Excel 的內建公式。 這種方法更可取——您的數據將以更現代、更優雅的方式處理。 該代碼易於理解和設置,無需聯繫技術支援或閱讀手冊。 這種方法在容器化環境中尤其有價值,因為在容器化環境中,你需要基於公式的計算並自動更新。 如何使基於公式的摘要自動更新? // Load the workbook WorkBook workbook = WorkBook.Load(inputPath); // Rename the first worksheet so formulas reference correctly WorkSheet dataSheet = workbook.WorkSheets[0]; dataSheet.Name = "DataSheet"; // Convert worksheet to DataTable DataTable dataTable = dataSheet.ToDataTable(true); // Create new summary worksheet WorkSheet summarySheet = workbook.CreateWorkSheet("DynamicSummary"); // Get unique product-region combinations var uniqueCombos = dataTable.AsEnumerable() .Select(row => new { Product = row["Product"].ToString(), Region = row["Region"].ToString() }) .Distinct() .OrderBy(x => x.Product) .ThenBy(x => x.Region); // Add header row summarySheet["A1"].Value = "Product"; summarySheet["B1"].Value = "Region"; summarySheet["C1"].Value = "Total Sales"; summarySheet["D1"].Value = "Count"; // Populate rows with formulas int rowIndex = 2; foreach (var combo in uniqueCombos) { summarySheet[$"A{rowIndex}"].Value = combo.Product; summarySheet[$"B{rowIndex}"].Value = combo.Region; // Adjust column references if your Sales column is C (not D) summarySheet[$"C{rowIndex}"].Formula = $"=SUMIFS(DataSheet!C:C,DataSheet!A:A,\"{combo.Product}\",DataSheet!B:B,\"{combo.Region}\")"; summarySheet[$"D{rowIndex}"].Formula = $"=COUNTIFS(DataSheet!A:A,\"{combo.Product}\",DataSheet!B:B,\"{combo.Region}\")"; rowIndex++; } // Optional: add total row summarySheet[$"A{rowIndex}"].Value = "Total"; summarySheet[$"C{rowIndex}"].Formula = $"=SUM(C2:C{rowIndex - 1})"; summarySheet[$"D{rowIndex}"].Formula = $"=SUM(D2:D{rowIndex - 1})"; // Save output file workbook.SaveAs(outputPath); //filename // Load the workbook WorkBook workbook = WorkBook.Load(inputPath); // Rename the first worksheet so formulas reference correctly WorkSheet dataSheet = workbook.WorkSheets[0]; dataSheet.Name = "DataSheet"; // Convert worksheet to DataTable DataTable dataTable = dataSheet.ToDataTable(true); // Create new summary worksheet WorkSheet summarySheet = workbook.CreateWorkSheet("DynamicSummary"); // Get unique product-region combinations var uniqueCombos = dataTable.AsEnumerable() .Select(row => new { Product = row["Product"].ToString(), Region = row["Region"].ToString() }) .Distinct() .OrderBy(x => x.Product) .ThenBy(x => x.Region); // Add header row summarySheet["A1"].Value = "Product"; summarySheet["B1"].Value = "Region"; summarySheet["C1"].Value = "Total Sales"; summarySheet["D1"].Value = "Count"; // Populate rows with formulas int rowIndex = 2; foreach (var combo in uniqueCombos) { summarySheet[$"A{rowIndex}"].Value = combo.Product; summarySheet[$"B{rowIndex}"].Value = combo.Region; // Adjust column references if your Sales column is C (not D) summarySheet[$"C{rowIndex}"].Formula = $"=SUMIFS(DataSheet!C:C,DataSheet!A:A,\"{combo.Product}\",DataSheet!B:B,\"{combo.Region}\")"; summarySheet[$"D{rowIndex}"].Formula = $"=COUNTIFS(DataSheet!A:A,\"{combo.Product}\",DataSheet!B:B,\"{combo.Region}\")"; rowIndex++; } // Optional: add total row summarySheet[$"A{rowIndex}"].Value = "Total"; summarySheet[$"C{rowIndex}"].Formula = $"=SUM(C2:C{rowIndex - 1})"; summarySheet[$"D{rowIndex}"].Formula = $"=SUM(D2:D{rowIndex - 1})"; // Save output file workbook.SaveAs(outputPath); //filename Imports System.Data Imports System.Linq ' Load the workbook Dim workbook As WorkBook = WorkBook.Load(inputPath) ' Rename the first worksheet so formulas reference correctly Dim dataSheet As WorkSheet = workbook.WorkSheets(0) dataSheet.Name = "DataSheet" ' Convert worksheet to DataTable Dim dataTable As DataTable = dataSheet.ToDataTable(True) ' Create new summary worksheet Dim summarySheet As WorkSheet = workbook.CreateWorkSheet("DynamicSummary") ' Get unique product-region combinations Dim uniqueCombos = dataTable.AsEnumerable() _ .Select(Function(row) New With { .Product = row("Product").ToString(), .Region = row("Region").ToString() }) _ .Distinct() _ .OrderBy(Function(x) x.Product) _ .ThenBy(Function(x) x.Region) ' Add header row summarySheet("A1").Value = "Product" summarySheet("B1").Value = "Region" summarySheet("C1").Value = "Total Sales" summarySheet("D1").Value = "Count" ' Populate rows with formulas Dim rowIndex As Integer = 2 For Each combo In uniqueCombos summarySheet($"A{rowIndex}").Value = combo.Product summarySheet($"B{rowIndex}").Value = combo.Region ' Adjust column references if your Sales column is C (not D) summarySheet($"C{rowIndex}").Formula = $"=SUMIFS(DataSheet!C:C,DataSheet!A:A,""{combo.Product}"",DataSheet!B:B,""{combo.Region}"")" summarySheet($"D{rowIndex}").Formula = $"=COUNTIFS(DataSheet!A:A,""{combo.Product}"",DataSheet!B:B,""{combo.Region}"")" rowIndex += 1 Next ' Optional: add total row summarySheet($"A{rowIndex}").Value = "Total" summarySheet($"C{rowIndex}").Formula = $"=SUM(C2:C{rowIndex - 1})" summarySheet($"D{rowIndex}").Formula = $"=SUM(D2:D{rowIndex - 1})" ' Save output file workbook.SaveAs(outputPath) ' filename $vbLabelText $csharpLabel 這些公式與來源資料保持即時連接,當資料表變更時自動更新—類似於資料透視表刷新行為,但沒有互通依賴性。 這種方法非常適合需要產生動態報告而無需外部相依性的容器化微服務。 動態摘要能帶來哪些結果? 如果我們將這段程式碼應用到上一個範例中的範例 Excel 文件,我們將得到以下輸出: ! Excel電子表格顯示產品銷售數據,其中包含動態總結公式,顯示各個地區的產品(筆記型電腦、手機、平板電腦)及其計算出的總數和數量。 動態匯總方法提供即時計算,當來源資料變更時會自動更新,因此非常適合容器化環境中的自動化報告管道。 這樣就無需定期刷新資料透視表,並且可以在.NET MAUI和Blazor應用程式中無縫運行。 如何比較 C# 互通 和 IronXL 在資料透視表方面的表現? 方面 C# 互通 IronXL 辦公室要求 是的 - 完全安裝 否 - 獨立庫 平台支援 僅限 Windows 系統 Windows、Linux、macOS、Docker 記憶體管理 需要手動清理 COM 對象 自動 .NET 垃圾回收 部署 複雜 - 辦公室許可 簡單 - 單一 DLL 表現 Excel進程啟動緩慢 快速記憶體計算 雲端相容 否 - Azure 限制 是的 - 支援 Azure Functions 原生透視表 是的 無 - 聚合替代方案 發展速度 速度慢 - COM 複雜性 快速直覺的 API 容器支援 不 - 無法將 Office 容器化 是的-已支援 Docker。 健康檢查 困難 - COM 進程監控 簡易型 - 標準 .NET 監控 從DevOps角度來看,IronXL 的架構為現代部署場景提供了顯著優勢。 該程式庫能夠在沒有外部相依性的情況下在容器中運行,這意味著您可以建立輕量級的 Docker 映像,從而快速部署並高效擴展。 健康檢查可以使用標準的 .NET 模式來實現,該程式庫的安全特性包括DigiCert認證和無 COM 接口,從而減少了攻擊途徑。 你該選擇哪一種方法? 何時應該使用 C# 互通? 選擇C# 互通的條件: 必須使用 Excel 原生資料透視表對象 完全在 Windows 系統上運作,所有 Office 服務均已安裝。 僅部署到您管理的桌面系統 現有遺留程式碼依賴互通性 使用舊版 .NET Framework 您目前沒有容器化或遷移到雲端的計劃 IronXL在什麼情況下效果更佳? 選擇IronXL 的情況: 部署到伺服器或雲端環境(Azure、AWS) 建立可在容器中運行的跨平台應用程式 需要更高的效能,速度提升 40 倍 避免 Office 授權費用和部署複雜性 需要更簡單的程式碼,並具備自動許可證金鑰管理功能 支援 Mac、iOS、Android 和 Linux 系統 熟悉現代 .NET Core 和 .NET 5-10 的開發。 以程式設計方式配置資料透視表字段 建構可導出為各種格式的微服務 在 CI/CD 管線中實現自動化報告 為容器編排建立健康檢查端點 *不同電子表格格式之間的轉換 我們在使用 C# 建立資料透視表方面學到了什麼? 雖然 C# Excel Interop 可以建立原生透視表,但其部署限制和複雜性使其對於現代應用程式來說越來越不切實際,尤其是在容器化環境中。 IronXL透過資料聚合和基於公式的匯總提供強大的替代方案,消除了對 Office 的依賴,同時保持了分析能力。 對於正在尋找無需互通即可開發透視表的替代方案的開發人員和DevOps工程師來說,IronXL 提供了一條更優的途徑,避免了 COM 的複雜性,可在所有平台上運行,並簡化部署。 雖然沒有原生透視對象,但更大的靈活性、更好的性能以及無需 Office 許可的要求彌補了這一不足。 對於DevOps團隊而言,最重要的是 IronXL 能夠實現真正的基礎設施即程式碼,支援容器化部署、自動擴展以及與現代 CI/CD 管道的無縫整合。 該程式庫的綜合功能集包括條件格式設定、儲存格樣式設定、公式支援和資料驗證,使其成為現代 .NET 應用程式中 Excel 自動化的完整解決方案。 無論您是處理 CSV 檔案、管理工作表還是實作複雜的資料轉換,IronXL 都提供了一個一致且易於部署的 API。 !{--01001100010010010100001001010010010000010101001001011001010111110100011101000101010101 01000101111101010011010101000100000101010010010101000100010101000100010111110101011101001000110 1010101000100100001011111010100000101001001001111010001000101010101010000110101010100101010101011 10101010001010010010010010010000010100110001011111010000100100110001001111101000011010010111111010000110100101110-- 準備好升級您的 Excel 自動化流程,並使用現代 C# 建立資料透視表程式碼了嗎? 透過 NuGet 套件管理器,您可以在幾秒鐘內將 IronXL 整合到您的 C# 應用程式中。 試用免費試用版,消除生產應用程式中的互通依賴關係,簡化容器部署。 常見問題解答 什麼是 Excel 中的透視表? Excel 中的透視表是用於總結、分析、探索和展示資料的強大工具。它允許使用者將列轉換為行,反之亦然,從而實現動態資料分析。 為何要使用 IronXL 在 C# 中建立 Excel 資料透視表? IronXL 可讓開發人員在不依賴 Office Interop 的情況下,以 C# 建立 Excel 資料透視表,不需要安裝 Excel 並減少依賴性,是現代化且有效率的選擇。 IronXL 與 Excel 操作的 C# Interop 相比如何? 相較於需要安裝 Office 的 C# Interop,IronXL 提供了更精簡、更獨立的方法。IronXL.Excel 可簡化資料透視表和其他 Excel 作業的建立,而無需 Interop 的複雜性。 我可以在沒有安裝 Excel 的情況下產生資料透視表嗎? 是的,使用 IronXL,您可以在 C# 應用程式中產生資料透視表,而無需安裝 Excel,因為它是獨立於 Microsoft Office 運作的。 IronXL 適合大型資料集嗎? IronXL 專為有效率地處理大型資料集而設計,因此適用於需要強大資料操作和產生資料透視表的應用程式。 與傳統方法相比,使用 IronXL 有哪些優勢? IronXL 提供了一個現代化、無依賴性的替代方案,可取代 C# Interop 等傳統方法,提供易用性、彈性,並支援複雜的資料作業,而無需安裝 Excel。 使用 IronXL 製作透視表需要學習 VBA 嗎? 不,IronXL 可讓開發人員直接在 C# 中工作,以建立和管理資料透視表,而無需學習 VBA 或其他 Excel 專用的程式語言。 Curtis Chau 立即與工程團隊聊天 技術撰稿人 Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。 相關文章 發表日期 2026年2月15日 如何使用 OleDb vs IronXL.Excel 將 DataTable 匯出至 Excel C# 學習如何使用 OleDb vs IronXL.Excel 將 DataTable 匯出至 Excel C#。 閱讀更多 發表日期 2026年2月15日 如何在未安裝 Office 的情況下使用 IronXL 開啟 VB.NET 中的現有 Excel 檔案 了解如何使用 IronXL for .NET 在未安裝 Office 的情況下在 VB.NET 中開啟現有的 Excel 檔案。 閱讀更多 發表日期 2026年2月15日 C# CSV to XLSX:完整開發人員指南 使用 IronXL 在 C# 中將 CSV 轉換為 XLSX。載入 CSV 檔案、保留資料類型、新增圖表,以及匯出為 Excel 格式,而無需 Microsoft Office 的相依性。 閱讀更多 如何在 VB.NET 中將 `DataGridView` 匯出至 Excel如何使用 IronXL 在 C# 中將...
發表日期 2026年2月15日 如何使用 OleDb vs IronXL.Excel 將 DataTable 匯出至 Excel C# 學習如何使用 OleDb vs IronXL.Excel 將 DataTable 匯出至 Excel C#。 閱讀更多
發表日期 2026年2月15日 如何在未安裝 Office 的情況下使用 IronXL 開啟 VB.NET 中的現有 Excel 檔案 了解如何使用 IronXL for .NET 在未安裝 Office 的情況下在 VB.NET 中開啟現有的 Excel 檔案。 閱讀更多
發表日期 2026年2月15日 C# CSV to XLSX:完整開發人員指南 使用 IronXL 在 C# 中將 CSV 轉換為 XLSX。載入 CSV 檔案、保留資料類型、新增圖表,以及匯出為 Excel 格式,而無需 Microsoft Office 的相依性。 閱讀更多