日付軸
可能な使用シナリオ
ワークシートデータからチャートを作成し、そのデータに日付が使用されており、チャートの水平(カテゴリ)軸に日付がプロットされている場合、Aspose.cellsは自動的にカテゴリ軸を日付(時間軸)軸に変更します。 日付軸は、特定の間隔や基本単位(日数、月、年など)で、ワークシートの日付を年代順に表示します。ワークシート上の日付が順次に並んでいない場合や基本単位が同じでない場合でも、表示されます。 デフォルトでは、Aspose.cellsは、ワークシートデータの任意の2つの日付間の最小の差に基づいて、日付軸の基本単位を決定します。たとえば、株価のデータがあり、日付間の最小の差が7日の場合、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"); | |