2015-11-20 145 views
0

我有這樣的代碼:如何將值(不只是百分比)添加到Excel餅圖?

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); 
     . . . 

...產生這個餅圖:

enter image description here

我喜歡它不夠好,但我需要有內部的印刷價值(比如「Contracted Items」部分的「$ 361,779」,另一個也是適當的值)。我怎樣才能做到這一點?

+1

不知道如何用C#做到這一點,但在Excel中,選擇圖表,轉到佈局,然後選擇「數據標籤」,然後選擇你想要的位置。 – BruceWayne

+0

我需要在代碼中完成 - 是你的意思嗎?我已經這樣做了: contractChart.ApplyDataLabels(XlDataLabelsType.xlDataLabelsShowValue,XlDataLabelsType.xlDataLabelsShowLabel,true,false,false,true,false,true); ...但它只給我% –

+1

啊,我想你只需要改變你的一個'真/假'。查看[本頁](https://msdn.microsoft.com/zh-cn/library/microsoft.office.tools.excel.chart.applydatalabels.aspx?cs-save-lang=1&cs-lang=csharp#code -snippet-1) – BruceWayne

回答

1

在C#中, 「真/假」 是什麼決定什麼值顯示:

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 
) 

因此,調整TrueFalse適用。

0

與蝙蝠俠的信息做實驗,我想出了這個:

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

...產生這樣的:

enter image description here

我寧願不具備領先的 「0」百分比(它顯示「045」和「055」而不是更合理和經濟的「45」和「55」),但我可以和他們一起生活。

+1

只是想一想,百分比表示的數據有多餘的數字嗎?也許如果你編輯這些數字的格式,它會起作用。或者在創建圖表後嘗試右擊數據並調整爲兩位數? – BruceWayne