如何在二维图形中标记Excel X轴和Y轴

本文关键字:Excel 轴和 图形 二维 | 更新日期: 2023-09-27 18:06:01

我被一个看起来很简单的问题难住了,标记X轴和Y轴!

我正在用c#在VS2010中创建一个Excel图表。这是一个2D XY散点图。但是我不能控制X轴的标签!我只能控制Y轴的标签!我花了太多时间试图弄清楚这个问题,但已经放弃了。所以我在找人帮忙!下面是我的代码:

    private void showExcelXY_v2()
    {
        xla = new Microsoft.Office.Interop.Excel.Application();
        xla.Visible = true;
        Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
        Worksheet ws = (Worksheet)xla.ActiveSheet;
        // Now create the chart.
        ChartObjects chartObjs = (ChartObjects)ws.ChartObjects(Type.Missing);
        ChartObject chartObj = chartObjs.Add(100, 20, 500, 300);
        Microsoft.Office.Interop.Excel.Chart xlChart = chartObj.Chart;
        //add some data from your datasource like a dataset or like below.
        ws.Cells[1, 1] = "Value of n";
        ws.Cells[1, 2] = "Term";

        ws.Cells[2, 1] = "0";
        ws.Cells[2, 2] = "0";
        ws.Cells[3, 1] = "9181";
        ws.Cells[3, 2] = "0";
        ws.Cells[4, 1] = "9181";
        ws.Cells[4, 2] = "-377094";
        ws.Cells[5, 1] = "0";
        ws.Cells[5, 2] = "-377094";
        ws.Cells[6, 1] = "-9554";
        ws.Cells[6, 2] = "-329688";
        ws.Cells[7, 1] = "-9554";
        ws.Cells[7, 2] = "0";
        ws.Cells[8, 1] = "0";
        ws.Cells[8, 2] = "0";

        //set the source data and the chart type.
        Range chartRange = ws.get_Range("A2", "B" + "8");
        xlChart.SetSourceData(chartRange, Type.Missing);
        xlChart.ChartType = XlChartType.xlXYScatterLines;
        // Customize axes:
        Microsoft.Office.Interop.Excel.Axis xAxis = (Microsoft.Office.Interop.Excel.Axis)xlChart.Axes(XlAxisType.xlValue, XlAxisGroup.xlPrimary);
        xAxis.HasTitle = true;
        xAxis.AxisTitle.Text = "Above         Pressure (psi)          Below";
        Microsoft.Office.Interop.Excel.Axis yAxis = (Microsoft.Office.Interop.Excel.Axis)xlChart.Axes(XlAxisType.xlValue, XlAxisGroup.xlPrimary);
        yAxis.MajorTickMark = XlTickMark.xlTickMarkCross;
        yAxis.HasTitle = true;
        yAxis.AxisTitle.Text = "Compression (lbf)";
        // Add title:
        xlChart.HasTitle = true;
        xlChart.ChartTitle.Text = "XPak Performance Envelope" + ''n' + "(Open Top & Bottom)";
        // Remove legend:
        xlChart.HasLegend = false;
    }

这段代码的结果,当您逐步执行它时,显示X轴标签移到Y轴,然后被Y轴标签覆盖。没有东西指向X轴!

如何在二维图形中标记Excel X轴和Y轴

两个轴的定义方式相同:

xAxis = (Microsoft.Office.Interop.Excel.Axis)xlChart.Axes(XlAxisType.xlValue, XlAxisGroup.xlPrimary)
yAxis = (Microsoft.Office.Interop.Excel.Axis)xlChart.Axes(XlAxisType.xlValue, XlAxisGroup.xlPrimary)

x轴是"类别"轴,y轴是"价值"轴。在x轴上试试这个(修改后的):

xAxis = (Microsoft.Office.Interop.Excel.Axis)xlChart.Axes(XlAxisType.xlCategory, XlAxisGroup.xlPrimary)