如何使用c#在Excel中添加数据透视表?

我将如何创build基于已经在工作表中创build的表的数据的数据透视表?

尝试这样的事情:

Microsoft.Office.Interop.Excel.PivotTable pivotCache = Globals.ThisAddIn.Application.ActiveWorkbook.PivotCaches(). Create(Microsoft.Office.Interop.Excel.XlPivotTableSourceType.xlDatabase, hoursTable2, XlPivotTableVersionList.xlPivotTableVersion12). CreatePivotTable("PivotTable!R1C1", "PivotTable1", Type.Missing, XlPivotTableVersionList.xlPivotTableVersion12); Microsoft.Office.Interop.Excel.Shape myChart = lPivotWorksheet.Shapes.AddChart(); myChart.Chart.SetSourceData(pivotCache.TableRange1, Type.Missing); Globals.ThisAddIn.Application.ActiveWorkbook.ShowPivotChartActiveFields = true; Microsoft.Office.Interop.Excel.PivotField rowField = (Microsoft.Office.Interop.Excel.PivotField)pivotCache.PivotFields("FieldTitle1"); rowField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlRowField; pivotCache.AddDataField(pivotCache.PivotFields("FieldTitle2"), "Sum of Difference", Microsoft.Office.Interop.Excel.XlConsolidationFunction.xlSum); Microsoft.Office.Interop.Excel.PivotField pageField = (Microsoft.Office.Interop.Excel.PivotField)pivotCache.PivotFields("FieldTitle3"); pageField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlPageField; myChart.ScaleHeight(2, Microsoft.Office.Core.MsoTriState.msoFalse, Type.Missing); myChart.ScaleWidth(2, Microsoft.Office.Core.MsoTriState.msoFalse, Type.Missing); myChart.Left = 200; myChart.Top = 120; myChart.Chart.ChartTitle.Caption = "Chart Title"; 

贝比斯的回答让我走上了正轨。 我相信我的代码会更容易阅读。 数据透视表是使用此链接上的文档创build的。 我正在使用Excel 2007。

  // assign the new pivot table PivotTable pivotTable = (PivotTable)pivotSheet.PivotTables("pivotTableName"); // Create a pivot chart using a pivot table as its source Shape chartShape = pivotSheet.Shapes.AddChart(); chartShape.Chart.SetSourceData(pivotTable.TableRange1, Type.Missing); CurrentWorkbook.ShowPivotChartActiveFields = true; chartShape.Chart.ChartType = XlChartType.xlAreaStacked;