QXlsx 是一个用于处理Excel文件的开源C++库。它允许你在你的C++应用程序中读取和写入Microsoft Excel文件(.xlsx格式)。该库支持多种操作,包括创建新的工作簿、读取和写入单元格数据、格式化单元格、以及其他与Excel文件相关的功能。
关于QXlsx的下载、安装、包含到项目中,源代码中如何使用,请看
《QXlsx Qt操作excel-CSDN博客》
《QXlsx Qt操作excel(1)-CSDN博客》
本章节将详细介绍如何使用QXlsx给excel插入图表。
代码如下:
#include "xlsxdocument.h"
#include "xlsxformat.h"
#include "xlsxcellrange.h"
#include "xlsxchart.h"
#include "xlsxworkbook.h"
using namespace QXlsx;
void MainWindow::on_pushButton_clicked()
{
Document xlsx;
//初始化单元格中数据
for (int i = 1; i < 10; ++i) {
xlsx.write(i, 1, i * i * i); // A1:A9
xlsx.write(i, 2, i * i); // B1:B9
xlsx.write(i, 3, i * i - 1); // C1:C9
}
//插入饼图和饼图(3D)
Chart *pieChart = xlsx.insertChart(3, 3, QSize(300, 300));
pieChart->setChartType(Chart::CT_PieChart);
pieChart->addSeries(CellRange("A1:A9"));
pieChart->addSeries(CellRange("B1:B9"));
pieChart->addSeries(CellRange("C1:C9"));
Chart *pie3DChart = xlsx.insertChart(3, 9, QSize(300, 300));
pie3DChart->setChartType(Chart::CT_Pie3DChart);
pie3DChart->addSeries(CellRange("A1:C9"));
//插入条形图和条形图(3D)
Chart *barChart = xlsx.insertChart(23, 3, QSize(300, 300));
barChart->setChartType(Chart::CT_BarChart);
barChart->addSeries(CellRange("A1:C9"));
Chart *bar3DChart = xlsx.insertChart(23, 9, QSize(300, 300));
bar3DChart->setChartType(Chart::CT_Bar3DChart);
bar3DChart->addSeries(CellRange("A1:C9"));
//插入线图、线图(3D)
Chart *lineChart = xlsx.insertChart(43, 3, QSize(300, 300));
lineChart->setChartType(Chart::CT_LineChart);
lineChart->addSeries(CellRange("A1:C9"));
Chart *line3DChart = xlsx.insertChart(43, 9, QSize(300, 300));
line3DChart->setChartType(Chart::CT_Line3DChart);
line3DChart->addSeries(CellRange("A1:C9"));
//插入面积图和面积图(3D)
Chart *areaChart = xlsx.insertChart(63, 3, QSize(300, 300));
areaChart->setChartType(Chart::CT_AreaChart);
areaChart->addSeries(CellRange("A1:C9"));
Chart *area3DChart = xlsx.insertChart(63, 9, QSize(300, 300));
area3DChart->setChartType(Chart::CT_Area3DChart);
area3DChart->addSeries(CellRange("A1:C9"));
//插入散点图
Chart *scatterChart = xlsx.insertChart(83, 3, QSize(300, 300));
scatterChart->setChartType(Chart::CT_ScatterChart);
// Will generate three lines.
scatterChart->addSeries(CellRange("A1:A9"));
scatterChart->addSeries(CellRange("B1:B9"));
scatterChart->addSeries(CellRange("C1:C9"));
Chart *scatterChart_2 = xlsx.insertChart(83, 9, QSize(300, 300));
scatterChart_2->setChartType(Chart::CT_ScatterChart);
// Will generate two lines.
scatterChart_2->addSeries(CellRange("A1:C9"));
//圆环图
Chart *doughnutChart = xlsx.insertChart(103, 3, QSize(300, 300));
doughnutChart->setChartType(Chart::CT_DoughnutChart);
doughnutChart->addSeries(CellRange("A1:C9"));
xlsx.saveAs("chart.xlsx");
xlsx.deleteLater();
}