Why does this attempt to create a PivotTable (Excel Interop) fail?

前端 未结 1 1600
-上瘾入骨i
-上瘾入骨i 2020-12-21 12:23

Based on code I found here, I\'m trying to create a Pivot Table like so:

var range = _xlSheet.Range[_xlSheet.Cells[6, 1],
                           _xlSheet         


        
相关标签:
1条回答
  • 2020-12-21 12:35

    Without seeing the specifics of your workbook, it's hard to diagnose some of the issues you list. The basic means of generating a pivot table would be this:

    Range sourceData = _xlBook.Worksheets["Produce Usage by Month"].Range["A6:F94"];
    
    PivotCache pc = pch.Create(XlPivotTableSourceType.xlDatabase, sourceData);
    PivotTable pvt = pc.CreatePivotTable(sheet2.Range["A1"], "SummaryPivot");
    
    pvt.PivotFields("Col1").Orientation = XlPivotFieldOrientation.xlRowField;
    pvt.PivotFields("Col2").Orientation = XlPivotFieldOrientation.xlColumnField;
    pvt.AddDataField(pvt.PivotFields("Col3"), "Sum of Col3", XlConsolidationFunction.xlSum);
    

    It looks like your code is not being really explicit about some of the objects. For example Produce Usage by Month!A6:F94 means something to Excel (and is probably interpreted by VBA), but I think the interop libraries need more explicit declaration of objects. In strong typed, this would be what I listed for the sourceData object. sheet2 is therefore an Excel.Worksheet object.

    Regarding some of the warnings, such as overwrite warnings, if you change the DisplayAlerts property of the Excel application object to false, it will take care of many of these.

    0 讨论(0)
提交回复
热议问题