4

我正在使用 C# Excel API 生成一些报告。但是,Excel 在数据集中的第一个轴点和最小值之间以及最后一个轴点和数据集中的最大值之间会留下间隙。我的数据集按日期时间排序。如何强制 excel 将轴的下限和上限精确设置为数据集中的最小值和最大值,以便我看不到任何间隙?我可以通过在 excel 图表中手动设置最小/最大轴点来在 excel 中做到这一点。

但是有没有办法让 excel 自动执行此操作,或者使用数据集从我的 C# 应用程序中设置最小/最大点?

示例(标记的间隙) 在此处输入图像描述

希望这是有道理的。

谢谢

4

1 回答 1

4

[Edited] OK, I did some playing, and I've figured out how to set the vertical and horizontal axis range. This is working with Excel 2010.

Here, I clear all charts on the page and create a new one (_resultsSheet is an Excel.Worksheet):

var resultCharts = (ChartObjects)_resultsSheet.ChartObjects();
foreach (ChartObject ch in resultCharts)
{
    ch.Delete();
}
ChartObject resultChart = resultCharts.Add(150, 40, 300, 200);
_resultChartPage = resultChart.Chart;

Now set up the source - I've just used a predefined range of fixed values. You could scan your source to find the actual min and max values:

_resultChartRange = _resultsSheet.get_Range("J5", "K15");
_resultChartPage.SetSourceData(_resultChartRange);
_resultChartPage.ChartType = Excel.XlChartType.xlXYScatterLines;
_resultChartPage.HasLegend = false;

Now for the vertical axis setup:

Axis vertAxis = (Axis)resultChart.Chart.Axes(XlAxisType.xlValue, XlAxisGroup.xlPrimary);
vertAxis.HasMajorGridlines = true; // change this to whatever you wish
vertAxis.HasTitle = true;
vertAxis.AxisTitle.Text = "up the side";
vertAxis.MaximumScaleIsAuto = false;
vertAxis.MaximumScale = 500; // you can pick this based on your input
vertAxis.MinimumScaleIsAuto = false;
vertAxis.MinimumScale = 5;

now for the other axis. Note here I've used fixed times. To convert a time to an axis scale, just use the 24 hour time in decimal, divided by 24. Eg. 9:30pm is 21:30 which is 21.5 hours. Don't forget the (double) cast just in case you use to ints.

Axis horizAxis = resultChart.Chart.Axes(XlAxisType.xlCategory, XlAxisGroup.xlPrimary);
horizAxis.MaximumScaleIsAuto = false;
horizAxis.MaximumScale = (double)21.5 / 24; // 9:30 pm
horizAxis.MinimumScaleIsAuto = false;
horizAxis.MinimumScale = (double)13 / 24; // 1:00 pm
horizAxis.HasTitle = true;
horizAxis.AxisTitle.Text = "across the bottom";

and for those who "like to watch":

_resultsSheet.Activate();
_workBook.Application.Visible = true;
于 2012-11-22T08:09:05.677 回答