2012-10-11 54 views
6

¿Alguien sabe cómo hacer esto?Tabla de pivote EPPlus - Colapsar todo el campo

estoy usando EPPlus en .Net y han creado una tabla dinámica con 2 campos de fila y un campo de datos Resumen:

Dim Pivot As OfficeOpenXml.Table.PivotTable.ExcelPivotTable 
Pivot = wksPivot.PivotTables.Add(wksPivot.Cells("A1"), Datarange, "pName") 

Pivot.RowFields.Add(Pivot.Fields("Fld1")).Sort = Table.PivotTable.eSortType.Ascending 
Pivot.RowFields.Add(Pivot.Fields("Fld2")).Sort = Table.PivotTable.eSortType.Ascending 

Dim dtaFld As OfficeOpenXml.Table.PivotTable.ExcelPivotTableDataField 
dtaFld = Pivot.DataFields.Add(Pivot.Fields("XYZ")) 
dtaFld.Function = Table.PivotTable.DataFieldFunctions.Sum 

Todo funciona muy bien, pero yo quiero tener la tabla dinámica a comenzar, como se derrumbó cuando el usuario abre el libro (en excel, cuando está creando la tabla dinámica, puede hacer clic derecho en el elemento de datos y seleccionar "Expandir/contraer"> "Contraer todo el campo"

Hot can I do this a través del código ?? (Y estoy dispuesto a utilizar OpenXML directo si EPPlus aún no lo admite ...)

TAMBIÉN, ¿hay alguna manera de eliminar los datos brutos del libro de trabajo para que la tabla dinámica siga funcionando? Lo he intentado y, cuando abro el libro, ¿mi tabla dinámica está en blanco? - Mi lógica actual me ha llevado al this question ... ¿Alguna idea?

(sí sé que escribí esta pregunta en VB pero añade tanto los C# & VB etiquetas a esta pregunta -. Me siento cómodo con el código en uno u otro idioma - Gracias !!)

+0

Como complemento a esta pregunta, ya que nadie ha respondido, lo que terminó haciendo fue la creación de la hoja con la tabla de datos usando EPPlus para la velocidad, a continuación, guardarlo . ENTONCES, abrí la hoja usando la interfaz Excel.Interop, creé la tabla dinámica y usé "Field1.ShowDetail = False" para colapsarla como quería ... –

+0

Como complemento de mi complemento ... El El comentario anterior ya no me sirve porque ahora quiero mover esta aplicación a ASP/IIS y Excel Interop ya no es una posibilidad válida ... –

Respuesta

-1

Uso EPPlus usted podría intentar algo así como (Tomado de this SO post):

(from pf in pivot.Fields 
select pf).ToList().ForEach(f => 
{ 
    f.Compact = false; 
    f.Outline = false; 
}); 

o tal vez más simplemente, no hace algo como lo siguiente trabajo?

pvtTable.Compact = False 
pvtTable.CompactData = False 
pvtTable.Outline = False 
pvtTable.OutlineData = False 
pvtTable.ShowDrill = True 

También se fijan en this SO post detalla un método de ingeniería inversa agradable para ver cómo sobresalir 'cosas' alcance.

P.S. No puedo ayudarte con tu otra pregunta 'también', perdón.

+0

Paul, no parece cambiar la tabla pivotante completamente colapsada ... ¿Lo lograste usando este código? ¡¡¡¡Gracias por la respuesta!!!! –

2

Podría convertirlo en xlsm y agregarle vba. Esta es probablemente la peor respuesta a esta solución, pero logra un colapso total. He proporcionado un ejemplo de trabajo, simplemente copie el pasado en una nueva aplicación de consola. agregue la dependencia de epplus, "F5".

modificado/tomado de http://epplus.codeplex.com/SourceControl/latest#SampleApp/Sample15.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using OfficeOpenXml.Table; 
using OfficeOpenXml.Table.PivotTable; 
using OfficeOpenXml; 
using System.IO; 

namespace pTable 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      //ExcelPackage _pck = new ExcelPackage(); 

      Directory.CreateDirectory(string.Format("Test")); 
      //ExcelPackage _pck = new ExcelPackage(new FileInfo("Test\\Worksheet.xlsx")); 
      ExcelPackage _pck = new ExcelPackage(new FileInfo("Test\\Worksheet.xlsm")); 

      var wsPivot1 = _pck.Workbook.Worksheets.Add("Rows-Data on columns"); 

      var ws = _pck.Workbook.Worksheets.Add("Data"); 
      ws.Cells["K1"].Value = "Item"; 
      ws.Cells["L1"].Value = "Category"; 
      ws.Cells["M1"].Value = "Stock"; 
      ws.Cells["N1"].Value = "Price"; 
      ws.Cells["O1"].Value = "Date for grouping"; 

      ws.Cells["K2"].Value = "Crowbar"; 
      ws.Cells["L2"].Value = "Hardware"; 
      ws.Cells["M2"].Value = 12; 
      ws.Cells["N2"].Value = 85.2; 
      ws.Cells["O2"].Value = new DateTime(2010, 1, 31); 

      ws.Cells["K3"].Value = "Crowbar"; 
      ws.Cells["L3"].Value = "Hardware"; 
      ws.Cells["M3"].Value = 15; 
      ws.Cells["N3"].Value = 12.2; 
      ws.Cells["O3"].Value = new DateTime(2010, 2, 28); 

      ws.Cells["K4"].Value = "Hammer"; 
      ws.Cells["L4"].Value = "Hardware"; 
      ws.Cells["M4"].Value = 550; 
      ws.Cells["N4"].Value = 72.7; 
      ws.Cells["O4"].Value = new DateTime(2010, 3, 31); 

      ws.Cells["K5"].Value = "Hammer"; 
      ws.Cells["L5"].Value = "Hardware"; 
      ws.Cells["M5"].Value = 120; 
      ws.Cells["N5"].Value = 11.3; 
      ws.Cells["O5"].Value = new DateTime(2010, 4, 30); 

      ws.Cells["K6"].Value = "Crowbar"; 
      ws.Cells["L6"].Value = "Hardware"; 
      ws.Cells["M6"].Value = 120; 
      ws.Cells["N6"].Value = 173.2; 
      ws.Cells["O6"].Value = new DateTime(2010, 5, 31); 

      ws.Cells["K7"].Value = "Hammer"; 
      ws.Cells["L7"].Value = "Hardware"; 
      ws.Cells["M7"].Value = 1; 
      ws.Cells["N7"].Value = 4.2; 
      ws.Cells["O7"].Value = new DateTime(2010, 6, 30); 

      ws.Cells["K8"].Value = "Saw"; 
      ws.Cells["L8"].Value = "Hardware"; 
      ws.Cells["M8"].Value = 4; 
      ws.Cells["N8"].Value = 33.12; 
      ws.Cells["O8"].Value = new DateTime(2010, 6, 28); 

      ws.Cells["K9"].Value = "Screwdriver"; 
      ws.Cells["L9"].Value = "Hardware"; 
      ws.Cells["M9"].Value = 1200; 
      ws.Cells["N9"].Value = 45.2; 
      ws.Cells["O9"].Value = new DateTime(2010, 8, 31); 

      ws.Cells["K10"].Value = "Apple"; 
      ws.Cells["L10"].Value = "Groceries"; 
      ws.Cells["M10"].Value = 807; 
      ws.Cells["N10"].Value = 1.2; 
      ws.Cells["O10"].Value = new DateTime(2010, 9, 30); 

      ws.Cells["K11"].Value = "Butter"; 
      ws.Cells["L11"].Value = "Groceries"; 
      ws.Cells["M11"].Value = 52; 
      ws.Cells["N11"].Value = 7.2; 
      ws.Cells["O11"].Value = new DateTime(2010, 10, 31); 
      ws.Cells["O2:O11"].Style.Numberformat.Format = "yyyy-MM-dd"; 

      var pt = wsPivot1.PivotTables.Add(wsPivot1.Cells["A1"], ws.Cells["K1:N11"], "Pivottable1"); 

      pt.Compact = true; 
      pt.CompactData = true; 

      pt.GrandTotalCaption = "Total amount"; 
      pt.RowFields.Add(pt.Fields[1]); 
      pt.RowFields.Add(pt.Fields[0]); 
      pt.DataFields.Add(pt.Fields[3]); 
      pt.DataFields.Add(pt.Fields[2]); 
      pt.DataFields[0].Function = DataFieldFunctions.Product; 
      pt.DataOnRows = false; 



      _pck.Workbook.CreateVBAProject(); 

      var sb = new StringBuilder(); 

      sb.AppendLine("Private Sub Workbook_Open()"); 
      sb.AppendLine(" Range(\"A1\").Select"); 
      sb.AppendLine(" ActiveSheet.PivotTables(\"Pivottable1\").PivotFields(\"Category\").PivotItems(\"Hardware\").ShowDetail = False"); 
      sb.AppendLine("End Sub"); 

      _pck.Workbook.CodeModule.Code = sb.ToString(); 

      _pck.Save(); 


     } 

    } 
} 
+0

Sabes qué, @FaceToDesk, estaba pensando en hacer esto una y otra vez y HOPING había una solución mejor, pero REALMENTE no parece que haya una basada en la falta de respuestas que esta pregunta ha recibido. Muchas gracias, creo que estás 100% en lo cierto y esta es la mejor manera de lidiar con el problema. –

+0

Creo que voy a mezclar esto con hacer que el Sub 'Workbook_Open' se elimine por sí mismo después de ejecutarse la primera vez ... Como se muestra aquí: http://www.excelforum.com/excel-programming-vba -macros/532200-how-to-remove-workbook_open-macro.html.Voy a publicar mi código final una vez que haya terminado para mostrar a cualquier persona que tenga este tipo de problema lo que se puede hacer. Solo por HOPING puedo obtener otra solución, no voy a marcarte como la respuesta correcta por el momento (Todavía estoy esperando que alguien tenga otra respuesta), ¡pero definitivamente mereces la recompensa! ¡¡¡¡Muchas gracias por tu ayuda!!!! –