日期轴
可能的使用场景
当您从工作表数据创建图表并使用日期时,日期会沿图表中的水平(类别)轴绘制,并且Aspose.Cells会自动将类别轴更改为日期(时间刻度)轴。 日期轴以特定间隔或基本单位(例如天数、月份或年份)按年代顺序显示日期,即使工作表上的日期不是按顺序或基本单位相同。 默认情况下,Aspose.Cells会根据工作表数据中任意两个日期之间的最小差异确定日期轴的基本单位。例如,如果您拥有股价数据,日期之间的最小差异为七天,Excel会将基本单位设置为天数,但是如果您想要查看股票在较长时间内的表现,可以将基本单位更改为月份或年份。
处理日期轴就像处理Microsoft Excel一样
请参阅以下样本代码,创建一个新的Excel文件并在第一个工作表中放置图表的值。 然后,我们添加一个图表并设置Axis的类型 到TimeScale,然后将基本单位设置为天数。
以下示例代码生成了输出Excel文件。
示例代码
// Create an instance of Workbook | |
Workbook workbook = new Workbook(); | |
// Get the first worksheet | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
// Add the sample values to cells | |
worksheet.getCells().get("A1").putValue("Date"); | |
// 14 means datetime format | |
Style style = worksheet.getCells().getStyle(); | |
style.setNumber(14); | |
// Put values to cells for creating chart | |
worksheet.getCells().get("A2").setStyle(style); | |
worksheet.getCells().get("A2").putValue(new DateTime(2022, 6, 26)); | |
worksheet.getCells().get("A3").setStyle(style); | |
worksheet.getCells().get("A3").putValue(new DateTime(2022, 5, 22)); | |
worksheet.getCells().get("A4").setStyle(style); | |
worksheet.getCells().get("A4").putValue(new DateTime(2022, 8, 3)); | |
worksheet.getCells().get("B1").putValue("Price"); | |
worksheet.getCells().get("B2").putValue(40); | |
worksheet.getCells().get("B3").putValue(50); | |
worksheet.getCells().get("B4").putValue(60); | |
// Adda chart to the worksheet | |
int chartIndex = worksheet.getCharts().add(ChartType.COLUMN, 9, 6, 21, 13); | |
// Access the instance of the newly added chart | |
Chart chart = worksheet.getCharts().get(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.getCategoryAxis().setCategoryType(CategoryType.TIME_SCALE); | |
// Set the base unit for CategoryAxis to days | |
chart.getCategoryAxis().setBaseUnitScale(TimeUnit.DAYS); | |
// Set the direction for the axis text to be vertical | |
chart.getCategoryAxis().getTickLabels().setDirectionType(ChartTextDirectionType.VERTICAL); | |
// Fill the PlotArea area with nothing | |
chart.getPlotArea().getArea().getFillFormat().setFillType(FillType.NONE); | |
// Set max value of Y axis. | |
chart.getValueAxis().setMaxValue(70); | |
// Set major unit. | |
chart.getValueAxis().setMajorUnit(10); | |
// Save the file | |
workbook.save("DateAxis.xlsx"); | |