LuckWallace
LuckWallace

Reputation: 133

Creating Pivot Table c# interop

I am trying to create a Pivot Table from a full Worksheet with C# interop but I am getting some errors, don't know if is my code or this example is old.

I am following this example: Creating a Pivot Table c#

But when I try it, I can't find some methods. This is my code:

            Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();

            Workbooks libro = Excel.Workbooks;
            Workbook libroActual = libro.Add();
            Sheets sheets = libroActual.Worksheets;

            //Excel.Workbooks.Add();

            // Instanciamos la hora activa
            Microsoft.Office.Interop.Excel._Worksheet Worksheet = Excel.ActiveSheet;
            Worksheet.Name = "Desglose";

            Worksheet sheetMMPP = Excel.Worksheets.Add();
            sheetMMPP.Name = "MMPP";// CreateEmptySheet(); 

            Microsoft.Office.Interop.Excel.Range dataRange = Worksheet.UsedRange;
            Microsoft.Office.Interop.Excel.PivotCache cache = (Microsoft.Office.Interop.Excel.PivotCache)libroActual.PivotCaches().Add(Microsoft.Office.Interop.Excel.XlPivotTableSourceType.xlDatabase,dataRange);
            Microsoft.Office.Interop.Excel.PivotTable pt = (Microsoft.Office.Interop.Excel.PivotTable)sheetMMPP.PivotTables().Add("Pivot Table", Worksheet.Range["A1"], cache);

            Microsoft.Office.Interop.Excel.PivotField oPivotField = (Microsoft.Office.Interop.Excel.PivotField)pt.PivotFields("Nivel 0");
            oPivotField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlDataField;
            oPivotField.Function = Microsoft.Office.Interop.Excel.XlConsolidationFunction.xlSum;
            oPivotField.Name = "Nivel 0";

But I get this error:

Could not convert argument 2 for call to Add

The error is in this line:

Microsoft.Office.Interop.Excel.PivotTable pt = (Microsoft.Office.Interop.Excel.PivotTable)sheetMMPP.PivotTables().Add("Pivot Table", Worksheet.Range["A1", "P56"], cache);

Someone knows about this error?

Upvotes: 1

Views: 1969

Answers (1)

basic
basic

Reputation: 11968

Looks like you've mixed up libraries. In your link, the example is based on the Spire.xls library, but in the code you use Interop.Excel with Spire syntax. The Interop.Excel PivotTables.Add method has different parameters - Add (Microsoft.Office.Interop.Excel.PivotCache PivotCache, object TableDestination, [object TableName], [object ReadData], [object DefaultVersion])

Upvotes: 2

Related Questions