如何将Excel数据透视表中的“子项”移动到另一列?

时间:2016-10-27 16:07:50

标签: excel pivot-table epplus epplus-4

我生成一张Excel表格,其中包含如下格式的数据:

enter image description here

IOW,“总包”,“总购买额”,“平均价格”和“总计百分比”值位于每个总体(或侧面)描述的自己(数据)列中。

当我透视数据提取此数据时,它会将这些值放在每个描述下面:

enter image description here

这是有道理的,但那些习惯于之前出现的人希望它能够在数据透视表中复制。如何将数据透视表中的描述“子项”移动到它们自己的列?

这是我用来生成数据透视表的代码:

private void PopulatePivotTableSheet()
{
    string NORTHWEST_CORNER_OF_PIVOT_TABLE = "A6";
    AddPrePivotTableDataToPivotTableSheet();
    var dataRange = rawDataWorksheet.Cells[rawDataWorksheet.Dimension.Address];
    dataRange.AutoFitColumns();
    var pivotTable = pivotTableWorksheet.PivotTables.Add(
                        pivotTableWorksheet.Cells[NORTHWEST_CORNER_OF_PIVOT_TABLE], 
                        dataRange, 
                        "PivotTable");
    pivotTable.MultipleFieldFilters = true;
    pivotTable.GridDropZones = false;
    pivotTable.Outline = false;
    pivotTable.OutlineData = false;
    pivotTable.ShowError = true;
    pivotTable.ErrorCaption = "[error]";
    pivotTable.ShowHeaders = true;
    pivotTable.UseAutoFormatting = true;
    pivotTable.ApplyWidthHeightFormats = true;
    pivotTable.ShowDrill = true;

    // Row field[s]
    var descRowField = pivotTable.Fields["Description"];
    pivotTable.RowFields.Add(descRowField);

    // Column field[s]
    var monthYrColField = pivotTable.Fields["MonthYr"];
    pivotTable.ColumnFields.Add(monthYrColField);

    // Data field[s]
    var totQtyField = pivotTable.Fields["TotalQty"];
    pivotTable.DataFields.Add(totQtyField);

    var totPriceField = pivotTable.Fields["TotalPrice"];
    pivotTable.DataFields.Add(totPriceField);

    // Don't know how to calc these vals here, so have to grab them from the source data sheet
    var avgPriceField = pivotTable.Fields["AvgPrice"];
    pivotTable.DataFields.Add(avgPriceField);

    var prcntgOfTotalField = pivotTable.Fields["PrcntgOfTotal"];
    pivotTable.DataFields.Add(prcntgOfTotalField);
}

因此,有一个RowField(“MonthYr”)具有诸如“201509”和“201510”之类的值,一个ColumnField(“Description”)和四个DataField,它们在Description列字段下对齐它们。我想将这四个字段向右移动到它们自己的列,并将Description标签在它们左边的四个值之间垂直居中。 [怎么样]这可能吗?

2 个答案:

答案 0 :(得分:2)

尝试使用

更改表格的布局
pivotTable.RowAxisLayout xlTabularRow
pivotTable.MergeLabels = True

这是结果:

enter image description here

C#中使用Interop.Excel的一个小脚本。包括使用;)

using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

var excelApp = new Excel.Application();
Excel.Workbook wb = excelApp.Workbooks.Open(@"e:\42\TestSO.xlsx");
Worksheet ws = wb.Worksheets["SheetName"];
PivotTable pt = ws.PivotTables("DynamicTableName");
pt.RowAxisLayout(XlLayoutRowType.xlTabularRow);
pt.MergeLabels = true;
wb.Save();
wb.Close();
Marshal.ReleaseComObject(ws);

答案 1 :(得分:1)

这是关于数据透视表布局/设计......这是手动方式 - 萨尔瓦多有VBA方式:)...

PivotTable Design