日期轴

可能的使用场景

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

像 Microsoft Excel 一样处理日期轴

请查看以下创建新 Excel 文件并将图表值放入第一个工作表的示例代码。 然后我们添加一个图表并设置图表的类型  到时标然后将基本单位设置为天。

待办事项:图片_替代_文本

示例代码

// 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