如何在数据透视表上设置列名称

问题描述 投票:0回答:2

使用这个答案我能够在 EPPlus 中创建一个具有表格布局的数据透视表。

但是,列标题无法正确显示。当我使用 Excel 创建数据透视表时,我得到列标题“GA Category”和“Container”: Pivot table by Excel


当我通过 EPPlus 创建数据透视表时,我得到列标题“行标签”和“列标签” Pivot table by EPPlus

我想知道如何通过 EPPlus 创建设置列标题。

vb.net pivot-table epplus
2个回答
7
投票

当前软件包无法通过 EPPLus 设置列标题。为此,我需要修改项目中的 ExcelPivotTable.cs,添加以下代码:

public string ColHeaderCaption
{
    get
    {
        return GetXmlNodeString("@colHeaderCaption");
    }
    set
    {
        SetXmlNodeString("@colHeaderCaption");
    }
}


然后可以通过数据透视表类设置行和列标题:

'Sheet containing the data
Dim dataSheet as ExcelWorksheet
dataSheet = package.Workbook.WorkSheets(0)

'Data used on pivot table - default to entire sheet
Dim dataRange as ExcelRangeBase
dataRange = dataSheet.Cells(dataSheet.Dimension.Address)

'New sheet for the pivot table
Dim sheet as ExcelWorkSheet
sheet = package.Workbook.Worksheets.Add("Pivot")
package.Workbook.Worksheets.MoveToStart(sheet.Name)
sheet.View.TabSelected = true

'Create the pivot table
Dim pivot as Table.PivotTable.ExcelPivotTable
pivot = sheet.PivotTables.Add(sheet.Cells("A1"), dataRange, "PivotTable")

'Add row field
pivot.RowFields.Add(pivot.Fields("RowField"))

'Set row caption
pivot.RowHeaderCaption = "My Row Caption"

'Add column field
pivot.ColumnFields.Add(pivot.Fields("ColumnField"))

'Set column caption
pivot.ColumnHeaderCaption = "My Column Caption"

如果您不能或不想修改 EPPlus,您仍然可以通过在创建数据透视表后修改 XML 来将标题添加到数据透视表中:

pivot.PivotTableXml.DocumentElement.SetAttribute("colHeaderCaption", "My Column Caption");

0
投票

EPPlus 5.5.5 为您提供了更轻松的设置选项:

pivotTable.RowHeaderCaption = "Account";
pivotTable.ColumnHeaderCaption = "Category";
© www.soinside.com 2019 - 2024. All rights reserved.