使用 C++ 自定义图表
创建自定义图表
到目前为止,在我们讨论图表时,我们只查看了具有其标准格式设置的标准图表。我们只定义数据源,设置几个属性,然后使用默认格式设置创建图表。但Aspose.Cells API также支持创建自定义图表,允许开发人员自己设置格式。
开发人员可以使用Aspose.Cells在运行时创建自定义图表。
图表由数据系列组成。在Aspose.Cells中,每个数据系列由Series对象表示,而SeriesCollection对象作为Series对象的集合。创建自定义图表时,开发人员可以自由选择不同类型的图表用于不同的数据系列(收集在SeriesCollection对象中)。
下面的示例代码演示了如何创建自定义图表。在此示例中,我们将为第一个数据系列使用柱形图,为第二个系列使用折线图。结果是,我们在工作表中添加了一个柱形图,结合了一条折线图。
#include <iostream>
#include "Aspose.Cells.h"
using namespace Aspose::Cells;
using namespace Aspose::Cells::Charts;
int main()
{
Aspose::Cells::Startup();
<span class="c1">// Source directory path
U16String srcDir(u"..\Data\01_SourceDirectory\");
<span class="c1">// Output directory path
U16String outDir(u"..\Data\02_OutputDirectory\");
<span class="c1">// Create a new workbook
Workbook workbook;
<span class="c1">// Add a new worksheet to the workbook
int sheetIndex = workbook.GetWorksheets().Add();
<span class="c1">// Obtain the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.GetWorksheets().Get(sheetIndex);
<span class="c1">// Add sample values to cells
worksheet.GetCells().Get(u"A1").PutValue(50);
worksheet.GetCells().Get(u"A2").PutValue(100);
worksheet.GetCells().Get(u"A3").PutValue(150);
worksheet.GetCells().Get(u"A4").PutValue(110);
worksheet.GetCells().Get(u"B1").PutValue(260);
worksheet.GetCells().Get(u"B2").PutValue(12);
worksheet.GetCells().Get(u"B3").PutValue(50);
worksheet.GetCells().Get(u"B4").PutValue(100);
<span class="c1">// Add a chart to the worksheet
int chartIndex = worksheet.GetCharts().Add(ChartType::Column, 5, 0, 15, 5);
<span class="c1">// Access the instance of the newly added chart
Chart chart = worksheet.GetCharts().Get(chartIndex);
<span class="c1">// Add NSeries (chart data source) to the chart ranging from "A1" cell to "B4"
chart.GetNSeries().Add(u"A1:B4", true);
<span class="c1">// Set the chart type of 2nd NSeries to display as line chart
chart.GetNSeries().Get(1).SetType(ChartType::Line);
<span class="c1">// Save the Excel file
workbook.Save(outDir + u"output.xls");
<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o"><<</span> <span class="s">"Chart created successfully!"</span> <span class="o"><<</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
<span class="n">Aspose</span><span class="o">::</span><span class="n">Cells</span><span class="o">::</span><span class="n">Cleanup</span><span class="p">();</span>
}
目前,Aspose.Cells仅支持结合饼图、折线图、柱状图和堆积柱状图的自定义图表,但未来版本将支持更多图表类型。