使用 IRONXL 如何在 C# 中创建 Excel 数据透视表 Curtis Chau 已发布:十月 27, 2025 Download IronXL NuGet 下载 DLL 下载 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 在业务应用程序中,通过程序处理Excel数据透视表是一项常见的需求,它需要分析和计算源数据。 虽然微软的Excel Interop一直是创建Excel文件中数据透视表的传统方法,但像IronXL这样的现代解决方案提供了显著的优势。 本指南详细介绍了这两种方法,提供实际示例,帮助您通过C# Interop创建Excel数据透视表,或选择更好的替代方案。 了解两种方法 什么是Excel Interop? Excel Interop使用COM(组件对象模型)通过C#直接控制Microsoft Excel。 它需要在系统上安装Office,基本上是自动执行Excel,仿佛用户正在与应用程序交互。 每个工作表、工作簿和单元格都变成了可以通过代码操作的对象。 什么是IronXL? IronXL是一个独立的.NET库,可以在不需要Microsoft Office的情况下读取、编辑和创建Excel文件。它兼容Windows、Linux、macOS和Docker容器,非常适合现代部署场景。 您可以打开、保存和导出数据,而无需COM interop的开销。 设置您的环境 关于Excel Interop Install-Package Microsoft.Office.Interop.Excel 关于IronXL Install-Package IronXL.Excel 或者,使用NuGet包管理器界面通过搜索"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 } } 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集合,能够自动处理内存。 输出 关键差异和注意事项 部署要求 Excel Interop需要: 安装Microsoft Excel并具有有效的许可证 Windows操作系统 正确的COM权限和设置 Office自动化的服务器配置 IronXL需要: 仅IronXL库包 在任何支持.NET的平台上运行 无需Office安装或许可证 简化的部署过程 代码质量和维护 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的免费试用开始体验不同,或探索教程以查看更多示例。 准备好部署了吗? 查看许可选项以选择适合您的任务的正确方案。 常见问题解答 使用 IronXL 创建数据透视表相对 Excel Interop 的优势是什么? IronXL 提供了相对于 Excel Interop 的显著优势,包括易用性、性能更优,以及无需在服务器上安装 Excel 即可创建数据透视表的能力。 我可以不使用 Excel Interop 而在 c# 中创建 Excel 数据透视表吗? 可以,您可以使用 IronXL 在 c# 中创建 Excel 数据透视表,这提供了 Excel Interop 的现代且高效的替代方案。 是否必须安装Microsoft Excel才能使用IronXL? 不,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 提供了多种许可选项,包括免费和付费档次,以适应不同项目需求和规模。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已发布十月 27, 2025 如何在C#中将DataGridView导出到包含列头的Excel 学习如何在将DataGridView数据导出到Excel时保留列头。使用IronXL库的C#逐步教程。 阅读更多 已发布十月 27, 2025 如何在.NET Core中使用CSV Reader与IronXL 学习通过实际示例有效地使用IronXL作为.NET Core的CSV读取器。 阅读更多 已发布十月 27, 2025 如何在C#中导出模板 了解如何有效地将C#数据导出到现有Excel模板,以使用IronXL优化你的工作流程。 阅读更多 如何在C#中导出模板
已发布十月 27, 2025 如何在C#中将DataGridView导出到包含列头的Excel 学习如何在将DataGridView数据导出到Excel时保留列头。使用IronXL库的C#逐步教程。 阅读更多