创建 Microsoft® Excel 图表并通过 C++ 转换为图像

将 Excel 文档图表转换为图像,并在基于 C++ 的应用程序中创建图表,包括饼图、金字塔图、折线图和气泡图。

 

使用 Excel 图表,人们可以了解更大的情况并轻松分析数据以做出正确的决策。 C++ Excel 库 支持创建列出的不同图表 枚举Aspose::Cells::图表::图表类型 包括面积图、条形图、饼图、金字塔图、折线图和气泡图。此外,为了将图表转换为图像,API 提供了 印象 方法转换为所需的图像格式。

创建 Excel 图表

创建Excel图表的过程是,创建一个实例 作业本类 并选择所需的 工作表 。使用添加图表 添加方法 以及相关参数,包括图表类型。通过索引访问图表 添加 图表的数据源。

C++ 创建 Excel 图表的代码
Aspose::Cells::Startup();
// Path of output XLSM file
U16String outputChartTypeCustom = u"sourceFile.xlsm";
// Create a new workbook
Workbook wkb;
// Get first worksheet which is created by default
Worksheet wks = wkb.GetWorksheets().Get(0);
// Adding sample values to cells
wks.GetCells().Get(u"A1").PutValue(50);
wks.GetCells().Get(u"A2").PutValue(100);
wks.GetCells().Get(u"A3").PutValue(150);
wks.GetCells().Get(u"B1").PutValue(4);
wks.GetCells().Get(u"B2").PutValue(20);
wks.GetCells().Get(u"B3").PutValue(50);
// Adding a chart to the worksheet
int chartIndex = wks.GetCharts().Add(Aspose::Cells::Charts::ChartType::Column, 5, 0, 20, 8);
// Accessing the instance of the newly added chart
Chart chart = wks.GetCharts().Get(chartIndex);
// Adding SeriesCollection (chart data source) to the chart ranging from "A1" cell to "B3"
chart.GetNSeries().Add(u"A1:B3", true);
// Saving the ODS file
wkb.Save(outputChartTypeCustom);
Aspose::Cells::Cleanup();

将图表转换为图像

对于转换图表的过程是,首先使用上面的代码创建相关类型的图表或从相关工作表访问它。定义图像的输出保存路径,并使用ToImage方法进行转换。

C++ 转换Excel图表的代码
Aspose::Cells::Startup();
// Output directory path
U16String outDir = u"..\\OutputDirectory\\";
// Path of output image file
U16String outputChartImage = outDir + u"out1image.png";
// Create a new workbook
Workbook wkb;
// Get first worksheet which is created by default
Worksheet wks = wkb.GetWorksheets().Get(0);
// Adding sample values to cells
wks.GetCells().Get(u"A1").PutValue(50);
wks.GetCells().Get(u"A2").PutValue(100);
wks.GetCells().Get(u"A3").PutValue(150);
wks.GetCells().Get(u"B1").PutValue(4);
wks.GetCells().Get(u"B2").PutValue(20);
wks.GetCells().Get(u"B3").PutValue(50);
// Adding a chart to the worksheet
int chartIndex = wks.GetCharts().Add(Aspose::Cells::Charts::ChartType::Column, 5, 0, 20, 8);
// Accessing the instance of the newly added chart
Chart chart = wks.GetCharts().Get(chartIndex);
// Adding SeriesCollection (chart data source) to the chart ranging from "A1" cell to "B3"
chart.GetNSeries().Add(u"A1:B3", true);
// Saving the chart to image file
chart.ToImage(outputChartImage, ImageType::Png);
Aspose::Cells::Cleanup();