简体   繁体   中英

How can I add the value (not just the percentage) to an Excel pie chart?

I've got this code:

private void WriteChartSheet()
{
    _xlSheetChart = (Worksheet)_xlSheets.Item[2];

    if (_xlSheetChart != null)
    {
        _xlSheetChart.Name = ProduceUsageChartSheetName;
        // Contract vs. non-Contract pie chart 
        _xlSheetChart.Cells[1, 1] = "Contracted Items";
        _xlSheetChart.Cells[1, 2] = "Non-Contracted Items";
        _xlSheetChart.Cells[2, 1] = GetContractedItemsTotal();
        _xlSheetChart.Cells[2, 2] = GetNonContractedItemsTotal();

        ChartObjects xlCharts = (ChartObjects)_xlSheetChart.ChartObjects(Type.Missing);
        ChartObject contractChartObject = xlCharts.Add(0, 0, 300, 250); // left, top, width, height
        Chart contractChart = contractChartObject.Chart;

        Range chartRange = _xlSheetChart.get_Range("A1", "B2");
        contractChart.SetSourceData(chartRange, Missing.Value);
        contractChart.ChartType = XlChartType.xlPie;  //xl3DPie;
        contractChart.ApplyDataLabels(XlDataLabelsType.xlDataLabelsShowValue, XlDataLabelsType.xlDataLabelsShowLabel, true, false, false, true, false, true);
        . . .

...that produces this pie chart:

在此处输入图片说明

I like it well enough, but I need to have the value printed within the pie pieces, too (such as "$361,779" for the "Contracted Items" piece, and the appropriate value for the other, also). How can I do that?

In C#, the "true/false" is what's determining what value is showing:

From here :

void ApplyDataLabels(
    XlDataLabelsType Type = XlDataLabelsType.xlDataLabelsShowValue,
    object LegendKey,
    object AutoText,
    object HasLeaderLines,
    object ShowSeriesName,
    object ShowCategoryName,
    object ShowValue,
    object ShowPercentage,
    object ShowBubbleSize,
    object Separator
)

So, adjust the True and False as applicable.

Experimenting with Batman's info, I came up with this:

contractChart.ApplyDataLabels(XlDataLabelsType.xlDataLabelsShowValue, false, true, false, false, false, true, true, false, false);

...that produces this:

在此处输入图片说明

I would prefer to not have the leading "0" in the percentages (it is displaying "045" and "055" rather than the more sensible and economical "45" and "55"), but I can live with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM