Obuli
Obuli

Reputation: 33

How can I place my data fields in COLUMNS in my Excel Pivot Table (Aspose Cells)

I have already tried "PivotFieldType.Column" approach. It's not working because the source data Excel sheet looks like below

Excel sheet: Input Data

Company Name FundsinUse LastDayCash

=======================

I am creating Pivot table from this "Input Data" sheet and the generated Excel looks like below:

Row Labels          
My Company AA    FundsinUse    -101544
                 LastDayCash    111
My Company BB    FundsinUse     8755
                 LastDayCash    222

I would like to get output like below:

Row Labels          FundsinUse        LastDayCash
My Company AA        -101544            111
My Company BB         8755              222

Please help me to implement "Drag To Colum" on Data Fields using C#

Sample code

string sourceData = string.Format("='Input Data'!A1:BU{0}", totalRows + 1);

int indexOfFirstSheet = workbookDesigner.Workbook.Worksheets["FirstSheet"].Index;

Worksheet newWS = workbookDesigner.Workbook.Worksheets.Insert(indexOfFirstSheet + 1, SheetType.Worksheet, "My Pivot Sheet");

PivotTableCollection pivotTablesColl = newWS.PivotTables;

int index = pivotTablesColl.Add(sourceData, "A3", "My Pivot");

PivotTable pt = pivotTablesColl[index];
pt.RowGrand = true;
pt.ColumnGrand = true;

//Row field
pt.AddFieldToArea(PivotFieldType.Row, "Company Name");

// Data fields
pt.AddFieldToArea(PivotFieldType.Data, "FundsinUse");
pt.AddFieldToArea(PivotFieldType.Data, "LastDayCash");

PivotField fundsinUse = pt.DataFields[0];
fundsinUse.DragToColumn = true;

Upvotes: 0

Views: 1167

Answers (3)

Scott Stafford
Scott Stafford

Reputation: 44818

For some reason, when you have two or more Data fields and no Column fields, you have to add a "virtual" field into the Columns to make it display as expected.

// Add virtual field to column
pt.AddFieldToArea(PivotFieldType.Column, pt.DataField);

See this for a fuller example: https://forum.aspose.com/t/how-do-you-add-a-count-column-to-a-pivottable/166240/8

Upvotes: 0

luis ort
luis ort

Reputation: 1

PivotTable pt = (PivotTable)hoja2.PivotTables("TD1");
pt.Format(XlPivotFormatType.xlReport1);

it´s works for me

Upvotes: 0

shakeel
shakeel

Reputation: 1725

Please use the PivotTable.DataField for your needs. Please see the following sample code and screenshots showing the input and output Excel files.

C#

Workbook wb = new Workbook("source.xlsx");

Worksheet ws = wb.Worksheets[0];

PivotTable pt = ws.PivotTables[0];

PivotField pdf = pt.DataField;

pt.AddFieldToArea(PivotFieldType.Column, pt.DataField);

pt.RefreshData();
pt.CalculateData();

wb.Save("output.xlsx");

Screenshot - Before

enter image description here

Screenshot - After

enter image description here

Note: I am working as Developer Evangelist at Aspose

Upvotes: 1

Related Questions