简体   繁体   中英

How to name axis in excel using C#?

This is how I create chart:

Excel.ChartObjects xlChartsq = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChartq = (Excel.ChartObject)xlChartsq.Add(10, 1000, 175, 310);
Excel.Chart chartPageq = myChartq.Chart;
myChartq.Select();

And I have succesfully named primary axis this way, I have used MDSN`s code :

Excel.Axis axis = myChartq.Chart.Axes(
Excel.XlAxisType.xlValue,
Excel.XlAxisGroup.xlPrimary);

axis.HasTitle = true;
axis.AxisTitle.Text = "AXIS`s NAME";

It works as should, but then I tried to use such method to name secondary axis, it failed:

Excel.Axis axisq = myChartq.Chart.Axes(
Excel.XlAxisType.xlValue,
Excel.XlAxisGroup.xlSecondary);

axisq.HasTitle = true; 
axisq.AxisTitle.Text = "another AXIS`s NAME";

It compiled without any errors, unfortunately after calling this code I got such error: unexpected exception " System.Runtime.InteropServices.COMException ", and something like HRESULT E_FAIL error was returned.

What am I doing wrong? Any suggestions?

UPD1: Before naming I create some series, but, honestly, I can't figure out how it can be associated with Secondary axis.

for (int i = 0; i < current_Excel_Position; i++ )
{
 Excel.Series series1 = seriesCollection.NewSeries();
 series1.XValues = xlWorkSheet.get_Range("A" + Convert.ToString(92 + i), "B" +     Convert.ToString(92 + i)); ;
 series1.Values = xlWorkSheet.get_Range("C" + Convert.ToString(92 + i), "D" + Convert.ToString(92 + i));
}

There has to be at least one series on the secondary axis. If all your data is on the primary axis you cannot show / edit the secondary axis.

Do you have any series on the secondary axis? If not that is your problem.

Edit: This is how you can set the value (Y axis in your case) and category (X axis in your case):

Excel.Axis axisq = myChartq.Chart.Axes(Excel.XlAxisType.xlValue,
               Excel.XlAxisGroup.xlPrimary);
axisq.HasTitle = true;
axisq.AxisTitle.Text = "Value axis NAME";

axisq = myChartq.Chart.Axes(Excel.XlAxisType.xlCategory,
                Excel.XlAxisGroup.xlPrimary);
axisq.HasTitle = true;
axisq.AxisTitle.Text = "Category axis NAME";

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