Excel VSTO + C#.NET +创build数据透视表

*用新的代码编辑如下

我试图通过Excel VSTO的C#.Net创build数据透视表,但不断收到一个exception抛出,指出:

Exception from HRESULT: 0x800A03EC 

我试图创build数据透视表的工作表称为oSheet,并且与具有源数据的工作表相同

我为数据透视表来源创build一个范围:

 Excel.Range pivotData = osheet.Range["A1", "B3"]; 

数据透视表的范围是:

 Excel.Range pivotDest = osheet.Range["A12", "B14"]; 

然后尝试用这个创build表格:

 osheet.PivotTableWizard( Excel.XlPivotTableSourceType.xlDatabase, pivotData, pivotDest, "Table", true, true, true, true, true, true, false, false, Excel.XlOrder.xlDownThenOver, 0, false, false ); 

表格向导行中发生错误。

任何想法是什么导致错误或更好的方式来创build一个数据透视表通过C#.Net?

*新代码

  Excel.Application oApp; Excel.Worksheet osheet; Excel.Workbook oBook; oApp = new Excel.Application(); oBook = oApp.Workbooks.Add(); osheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1); osheet.Cells[1, 1] = "Name"; osheet.Cells[1, 2] = "Salary"; osheet.Cells[2, 1] = "Frank"; osheet.Cells[2, 2] = 1500000; osheet.Cells[3, 1] = "Millford"; osheet.Cells[3, 2] = 2200; //Now capture range of first sheet = I will need this to create pivot table Excel.Range oRange = osheet.Range["A1", "B3"]; var pch = oBook.PivotCaches(); Excel.Range pivotData = osheet.Range["A1", "B3"]; Excel.PivotCache pc = pch.Create(XlPivotTableSourceType.xlDatabase, pivotData); Excel.PivotTable pvt = pc.CreatePivotTable(osheet.Range["A12"], "MyPivotTable"); pvt.PivotFields("Col1").Orientation = XlPivotFieldOrientation.xlRowField; pvt.PivotFields("Col2").Orientation = XlPivotFieldOrientation.xlColumnField; pvt.AddDataField(pvt.PivotFields("Col3"), "Sum of Col3", XlConsolidationFunction.xlSum); 

我刚刚回答了一个类似的问题,

https://stackoverflow.com/a/39968355/1278553

简而言之,在C#中创build数据透视表的方法是:

 Excel.Range pivotData = osheet.Range["A1", "B3"]; Excel.PivotCache pc = pch.Create(XlPivotTableSourceType.xlDatabase, pivotData); Excel.PivotTable pvt = pc.CreatePivotTable(osheet.Range["A12"], "MyPivotTable"); 

然后分配你的行/列和数据字段:

 pvt.PivotFields("Col1").Orientation = XlPivotFieldOrientation.xlRowField; pvt.PivotFields("Col2").Orientation = XlPivotFieldOrientation.xlColumnField; pvt.AddDataField(pvt.PivotFields("Col3"), "Sum of Col3", XlConsolidationFunction.xlSum); 

我剽窃我先前的答案。

– 编辑10/17/2016 –

根据您更新的代码,现在应该可以创build数据透视表:

 var pch = oBook.PivotCaches(); Excel.Range pivotData = osheet.Range["A1", "B3"]; Excel.PivotCache pc = pch.Create(Excel.XlPivotTableSourceType.xlDatabase, pivotData); Excel.PivotTable pvt = pc.CreatePivotTable(osheet.Range["A12"], "MyPivotTable"); pvt.PivotFields("Name").Orientation = Excel.XlPivotFieldOrientation.xlRowField; pvt.AddDataField(pvt.PivotFields("Salary"), "Total Salary", Excel.XlConsolidationFunction.xlSum);