4

我被一个看似简单的问题难住了,标记 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轴没有任何东西!任何想法将不胜感激。

4

1 回答 1

5

您以相同的方式定义了两个轴:

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)
于 2013-03-26T13:59:10.287 回答