日期轴

可能的使用场景

当您从工作表数据创建图表并使用日期时,日期会沿图表中的水平(类别)轴绘制,并且Aspose.Cells会自动将类别轴更改为日期(时间刻度)轴。 日期轴以特定间隔或基本单位(例如天数、月份或年份)按年代顺序显示日期,即使工作表上的日期不是按顺序或基本单位相同。 默认情况下,Aspose.Cells会根据工作表数据中任意两个日期之间的最小差异确定日期轴的基本单位。例如,如果您拥有股价数据,日期之间的最小差异为七天,Excel会将基本单位设置为天数,但是如果您想要查看股票在较长时间内的表现,可以将基本单位更改为月份或年份。

处理日期轴就像处理Microsoft Excel一样

请参阅以下样本代码,创建一个新的Excel文件并在第一个工作表中放置图表的值。 然后,我们添加一个图表并设置Axis的类型  到TimeScale,然后将基本单位设置为天数。

todo:image_alt_text

示例代码

// Create an instance of Workbook
Workbook workbook = new Workbook();
// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Add the sample values to cells
worksheet.Cells["A1"].PutValue("Date");
// 14 means datetime format
Style style = worksheet.Cells.Style;
style.Number = 14;
// Put values to cells for creating chart
worksheet.Cells["A2"].SetStyle(style);
worksheet.Cells["A2"].PutValue(new DateTime(2022, 6, 26));
worksheet.Cells["A3"].SetStyle(style);
worksheet.Cells["A3"].PutValue(new DateTime(2022, 5, 22));
worksheet.Cells["A4"].SetStyle(style);
worksheet.Cells["A4"].PutValue(new DateTime(2022, 8, 3));
worksheet.Cells["B1"].PutValue("Price");
worksheet.Cells["B2"].PutValue(40);
worksheet.Cells["B3"].PutValue(50);
worksheet.Cells["B4"].PutValue(60);
// Adda chart to the worksheet
int chartIndex = worksheet.Charts.Add(Aspose.Cells.Charts.ChartType.Column, 9, 6, 21, 13);
// Access the instance of the newly added chart
Aspose.Cells.Charts.Chart chart = worksheet.Charts[chartIndex];
// Add SeriesCollection (chart data source) to the chart ranging from "A1" cell to "B4"
chart.SetChartDataRange("A1:B4", true);
// Set the Axis type to Date time
chart.CategoryAxis.CategoryType = CategoryType.TimeScale;
// Set the base unit for CategoryAxis to days
chart.CategoryAxis.BaseUnitScale = TimeUnit.Days;
// Set the direction for the axis text to be vertical
chart.CategoryAxis.TickLabels.DirectionType = ChartTextDirectionType.Vertical;
// Fill the PlotArea area with nothing
chart.PlotArea.Area.FillFormat.FillType = FillType.None;
// Set max value of Y axis.
chart.ValueAxis.MaxValue = 70;
// Set major unit.
chart.ValueAxis.MajorUnit = 10;
// Save the file
workbook.Save("DateAxis.xlsx");
view raw DateAxis.cs hosted with ❤ by GitHub