我生成一个 Excel 工作表,其中包含格式如下的数据:
IOW,“总包数”、“总购买量”、“平均价格”和“占总数的百分比”值位于每个总体(或侧向)描述的自己的(数据)列中。
当我对这些数据进行数据透视表化时,它会将这些值放置在每个描述下方:
这是有道理的,但那些习惯了以前外观的人希望将其复制到数据透视表中。如何将数据透视表中的描述“子项目”移至其自己的列?
这是我用来生成数据透视表的代码:
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);
}
因此,有一个具有“201509”和“201510”等值的 RowField(“MonthYr”)、一个 ColumnField(“Description”)和四个 DataField,它们在“Description”列字段下对齐。我想将这四个字段向右移动到它们自己的列,并且“描述”标签在左侧的这四个值之间垂直居中。 [如何]这可能吗?
最佳答案
尝试使用以下命令更改表格的布局
pivotTable.RowAxisLayout xlTabularRow
pivotTable.MergeLabels = True
这是结果:
使用 Interop.Excel 编写的 C# 小脚本。包括使用;)
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);
关于excel - 如何将 Excel 数据透视表中的 "subitems"移动到另一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40289460/