Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi everyone!

I'm trying to generate a Pivot Table from a Excel file using C# with Visual Studio 2010 without using Spire.xls. For example, my sheet 1 have the information and I want to create a Sheet2 with the pivot table. I have seen a lot of examples but I can't run anyone...

In what have I tried you can see my code ...

What could am I doing wrong? Is there some example to create a Pivot Table using an existing excel sheet?

Thank you in advance!

What I have tried:

This is my code:
C#
//Usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.Globalization;

Workbooks libro = Excel.Workbooks;
Workbook libroActual = libro.Add();
Sheets sheets = libroActual.Worksheets;
Microsoft.Office.Interop.Excel._Worksheet Worksheet = libroActual.ActiveSheet; Worksheet.Name = "Desglose";

// Operations here with sheed 1

Worksheet sheetMMPP = sheets.Add();
sheetMMPP.Name = "MMPP";

//Range of the origin sheet
Microsoft.Office.Interop.Excel.Range oRange = Worksheet.UsedRange;
Microsoft.Office.Interop.Excel.Range oRange2 = sheetMMPP.Cells[1, 1]; 
Microsoft.Office.Interop.Excel.PivotCache oPivotCache = (Microsoft.Office.Interop.Excel.PivotCache)libroActual.PivotCaches().Add(Microsoft.Office.Interop.Excel.XlPivotTableSourceType.xlDatabase, oRange2);
Microsoft.Office.Interop.Excel.PivotCaches pch = libroActual.PivotCaches(); 
Microsoft.Office.Interop.Excel.PivotTable pvt = sheetMMPP.PivotTables("PivTbl_1") as Microsoft.Office.Interop.Excel.PivotTable;
Posted
Updated 9-Dec-19 1:21am
Comments
Richard MacCutchan 25-Nov-19 8:00am    
"What could am I doing wrong?"
Not telling us what the problem is.
Member 14667330 25-Nov-19 11:30am    
Thank Richard for try to help me.

The problem is that this example that I've tried is using Spire.xls and I have not that. Is there another way to do this? I am using interops and I turning mad looking for a solution for this...

Thank you in advance!
Richard MacCutchan 25-Nov-19 11:42am    
Sorry but that still does not tell us what is wrong with the above code. And if you need help with Spire.xls, then you should use their support forum at Support[^].
Member 14667330 25-Nov-19 11:51am    
That's the problem, I have been looking for create a pivot table and only found examples with Spire.xls ... So I would like to know how can I create a pivot table without use Spire. From the begginig of my code to the line "sheetMMPP.Name = "MMPP";" I know that this work fine but don't know how to create the pivot table from that line.

1 solution

 
Share this answer
 
Comments
Maciej Los 10-Dec-19 13:27pm    
Google is always good resource.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900