
如何在 C# 中创建 Excel 数据透视表
在业务应用程序中,通过程序处理Excel数据透视表是一项常见的需求,它需要分析和计算源数据。 虽然微软的Excel Interop一直是创建Excel文件中数据透视表的传统方法,但像IronXL这样的现代解决方案提供了显著的优势。 本指南详细介绍了这两种方法,并通过实际示例帮助您使用C#互操作创建数据透视表或选择更好的替代方案。
了解两种方法
什么是Excel Interop?
Excel Interop使用COM(组件对象模型)通过C#直接控制Microsoft Excel。 它需要在系统上安装Office,基本上是自动执行Excel,仿佛用户正在与应用程序交互。 每个工作表、工作簿和单元格都变成了可以通过代码操作的对象。
什么是IronXL?
IronXL是一个独立的.NET库,可以在不需要Microsoft Office的情况下读取、编辑和创建Excel文件。它兼容Windows、Linux、macOS和Docker容器,非常适合现代部署场景。 您可以打开、保存和导出数据,而无需COM interop的开销。
设置您的环境
关于Excel Interop
关于IronXL
或者,使用NuGet包管理器界面通过搜索"IronXL.Excel"并点击安装来安装。 您还可以通过.NET CLI使用命令参数安装,或直接从GitHub引用。
这两个库都可以通过NuGet获取。 请注意,Excel Interop需要完整的Microsoft Office安装,而IronXL可以独立运行。 在继续之前,请确保您的系统满足要求。
使用C#互操作以编程方式创建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
}
}Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Class Program
Shared Sub Main(ByVal args() As String)
' Create Excel application instance
Dim excelApp As New Excel.Application()
Dim workbook As Excel.Workbook = excelApp.Workbooks.Add()
Dim dataSheet As Excel.Worksheet = CType(workbook.Worksheets(1), Excel.Worksheet)
Dim pivotSheet As Excel.Worksheet = CType(workbook.Worksheets.Add(), Excel.Worksheet)
' 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
Dim dataRange As Excel.Range = dataSheet.Range("A1:C10")
Dim pivotCache As Excel.PivotCache = workbook.PivotCaches().Create(Excel.XlPivotTableSourceType.xlDatabase, dataRange)
' Create PivotTable at specific location
Dim pivotTables As Excel.PivotTables = CType(pivotSheet.PivotTables(), Excel.PivotTables)
Dim pivotTable As Excel.PivotTable = pivotTables.Add(pivotCache, pivotSheet.Range("A3"), "SalesPivot")
' Configure pivot table fields - row and column headers
CType(pivotTable.PivotFields("Product"), Excel.PivotField).Orientation = Excel.XlPivotFieldOrientation.xlRowField
CType(pivotTable.PivotFields("Region"), Excel.PivotField).Orientation = Excel.XlPivotFieldOrientation.xlColumnField
CType(pivotTable.PivotFields("Sales"), Excel.PivotField).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 Then
Marshal.ReleaseComObject(pivotTable)
Marshal.ReleaseComObject(pivotSheet)
Marshal.ReleaseComObject(dataSheet)
Marshal.ReleaseComObject(workbook)
Marshal.ReleaseComObject(excelApp)
#End If
End Sub
End Class此代码创建一个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");
}
}Imports IronXL
Imports System.Linq
Class Program
Shared Sub Main(args As String())
' Create workbook and add worksheet with data
Dim workbook As WorkBook = WorkBook.Create()
Dim sheet As WorkSheet = 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
Dim summarySheet = workbook.CreateWorkSheet("Summary")
' Group and calculate aggregated data
Dim data = sheet("A1:C10").ToDataTable(True)
Dim productSummary = data.AsEnumerable() _
.GroupBy(Function(row) row.Field(Of String)("Product")) _
.Select(Function(group, index) New With {
.Product = group.Key,
.TotalSales = group.Sum(Function(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
For Each 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
Next
' Apply number formatting and style
summarySheet("B:B").FormatString = "$#,##0.00"
' Save the xlsx file
workbook.SaveAs("analysis_ironxl.xlsx")
End Sub
End Class此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互操作开销,同时提供强大的数据操作能力。 无论您想读取、编辑还是导出Excel数据,IronXL都提供了一个更简洁的解决方案。
通过IronXL的免费试用开始体验不同,或探索教程以查看更多示例。 准备好部署了吗? 查看许可选项以选择适合您的任务的正确方案。

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。
相关文章



