【问题标题】:How to set column name on pivot table如何在数据透视表上设置列名
【发布时间】:2013-01-21 18:12:52
【问题描述】:

使用this answer 我能够在 EPPlus 中创建具有表格布局的数据透视表。

但是列标题显示不正确。当我使用 Excel 创建数据透视表时,我得到列标题“GA 类别”和“容器”:


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

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

【问题讨论】:

    标签: vb.net pivot-table epplus


    【解决方案1】:

    当前包无法通过 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");
    

    【讨论】:

    • 您应该提交一个包含此更改的拉取请求:)。仍然 +1 来解决这个问题。
    • 仅供参考,我查看了最新的源代码,您设置标题的代码就在那里。
    猜你喜欢
    • 2017-10-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 2016-12-23
    相关资源
    最近更新 更多