我在使用c#在excel中创建数据透视表时遇到了一个问题,其中创建的数据透视表一旦创建并添加到工作表中,便会显示其他空列(它们仍然是数据透视表的一部分)。
所有数据透视表字段的方向都设置为Excel.XlPivotFieldOrientation.xlRowField。如果我手动将字段之一拖到Excel中数据透视表的“值”部分中,则该表似乎正确显示。如果删除它,其他空白列将再次显示。
下面是创建数据透视表的功能:
public void CreatePivotTable(Excel.Workbook workbook, Excel.Worksheet worksheet, Excel.Range sourceRange)
{
object useDefault = Type.Missing;
Excel.PivotTable pivotTable;
Excel.Range pivotData;
Excel.Range pivotDestination;
Excel.PivotField parentNameField;
Excel.PivotField parameterNameField;
Excel.PivotField parameterTypeField;
Excel.PivotField parameterValueField;
string pivotTableName = "ParametersPivot";
pivotData = sourceRange;
pivotDestination = worksheet.Range["A15", "A15"];
Excel.PivotCache pivotCache = workbook.PivotCaches().Create(Excel.XlPivotTableSourceType.xlDatabase, sourceRange, Type.Missing);
Excel.PivotTables pivotTables = worksheet.PivotTables(Type.Missing);
pivotTable = pivotTables.Add(pivotCache, pivotDestination, pivotTableName, Type.Missing, Type.Missing);
pivotTable.ColumnGrand = false;
pivotTable.RowGrand = false;
pivotTable.HasAutoFormat = true;
pivotTable.
parentNameField = (Excel.PivotField)pivotTable.PivotFields(1);
parentNameField.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
parameterNameField = (Excel.PivotField)pivotTable.PivotFields(2);
parameterNameField.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
parameterTypeField = (Excel.PivotField)pivotTable.PivotFields(3);
parameterTypeField.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
parameterValueField = (Excel.PivotField)pivotTable.PivotFields(4);
parameterValueField.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
//Format the Pivot Table.
pivotTable.Format(Excel.XlPivotFormatType.xlPTNone);
pivotTable.InGridDropZones = false;
pivotTable.SmallGrid = false;
pivotTable.ShowTableStyleRowStripes = false;
pivotTable.TableStyle2 = "PivotStyleMedium8";
//// Page Field
//parentNameField.Orientation = Excel.XlPivotFieldOrientation.xlPageField;
//parentNameField.Position = 1;
//parentNameField.CurrentPage = "(All)";
}
Any field dragged to pivot values section
Resulting pivot table after dragging field to values section