Visual Studio Excel数据透视表不显示数据

我正在编写一个应用程序来在现有的Excel工作簿中添加数据透视表工作表。 代码如下:

Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); if (e.Name.StartsWith("~$")) return; Excel.Application oApp; Excel.Worksheet oSheet; Excel.Workbook oBook; oApp = new Excel.Application(); try { oBook = oApp.Workbooks.Open(e.FullPath); oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1); //Excel.Range finalCell = oSheet.Cells[2, oSheet.Rows.Count]; Excel.Range oRange = oSheet.get_Range("A1", "M9"); if (oApp.Application.Sheets.Count < 2) { oSheet = (Excel.Worksheet)oBook.Worksheets.Add(); } else { oSheet = oApp.Worksheets[2]; } oSheet.Name = "Pivot Table"; // specify first cell for pivot table Excel.Range oRange2 = oSheet.Cells[3,1]; // create Pivot Cache and Pivot Table Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange); Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary"); Excel.PivotField oPivotField1 = (Excel.PivotField)oPivotTable.PivotFields("Field1"); oPivotField1.Orientation = Excel.XlPivotFieldOrientation.xlRowField; oPivotField1.Position = 1; oPivotField1.Name = "Field1"; Excel.PivotField oPivotField2 = (Excel.PivotField)oPivotTable.PivotFields("Field2"); oPivotField2.Orientation = Excel.XlPivotFieldOrientation.xlRowField; oPivotField2.Position = 2; oPivotField2.Name = "Field2"; oBook.Save(); Console.WriteLine("Operation Complete"); } 

这是在FileSystemWatcher的文件创build事件处理程序中。 该程序运行并创buildPivot表的工作表,但数据值不列出,我也得到两个单独的列。 这是屏幕

请让我知道我做错了什么。 使用Visual Studio 2015和项目types是Windows窗体应用程序。

replace数据透视表caching/表创build行:

 Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange); Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary"); 

 PivotCache oPivotCache = oBook.PivotCaches().Create(XlPivotTableSourceType.xlDatabase, oRange, XlPivotTableVersionList.xlPivotTableVersion14); PivotTable oPivotTable = oPivotCache.CreatePivotTable(TableDestination: oRange2, TableName: "Summary"); 

请注意,您正在进行大量冗余投射。 您通常不必转换所有的pivotCache和pivotfieldvariables。